Angular Testing: From First Test to Large Suites
Why this matters
Section titled “Why this matters”Most Angular test suites fail in one of two ways. They test so little that a green run means nothing, or they test the implementation so tightly that every refactor breaks hundreds of specs and the team stops refactoring.
Both are design problems, not tooling problems. This guide covers the current Angular CLI testing baseline and, more importantly, how to decide what to test so the suite stays worth running.
Terminology and the current baseline
Section titled “Terminology and the current baseline”Angular’s CLI testing defaults changed materially. On a current project:
- Vitest is the default test runner. New CLI projects include
vitestandjsdom. jsdomsimulates the DOM in Node — no browser launch, which is why it is fast.happy-domis the supported alternative; those two are the supported DOM emulation libraries.- Karma is still supported but is no longer the default, and there is an official migration path.
ng testruns in watch mode when you are on an interactive terminal, and turns watch off on CI automatically.
ng test ✓ src/app/orders/order-list.spec.ts (4) Test Files 1 passed (1) Tests 4 passed (4) Duration 2.46sIf you are on an older project, Jasmine + Karma is the legacy baseline. It still works. Migration is covered near the end.
The mental model: what a test costs
Section titled “The mental model: what a test costs”Every test has a price — authoring time, run time, and maintenance under refactor. That third cost is the one teams ignore, and it is the one that kills suites.
HIGH maintenance cost LOW maintenance cost ───────────────────── ─────────────────── "component calls service.load()" "the order total is displayed" "spy was called with 3 args" "clicking Save submits once" "private method sorted the array" "invalid form blocks submit" │ │ breaks on every refactor breaks only when behaviour changesTest observable behaviour, not internal wiring. A test that asserts a spy was called is a test that fails when you rename a method — while a genuinely broken feature can still pass it.
What not to unit test
Section titled “What not to unit test”- Framework behaviour. Do not test that
@ifhides an element. Angular tests Angular. - Trivial getters, constants, and pure pass-through code.
- Third-party libraries. Test your integration with them, not them.
- Private methods. If a private method needs a test, it wants to be a separate function or service.
Time saved here buys integration tests that actually catch regressions.
Minimal correct example
Section titled “Minimal correct example”The smallest test that proves something real:
import { TestBed } from '@angular/core/testing';import { OrderTotalComponent } from './order-total.component';
describe('OrderTotalComponent', () => { it('renders the formatted total', async () => { await TestBed.configureTestingModule({ imports: [OrderTotalComponent], // standalone: import, don't declare }).compileComponents();
const fixture = TestBed.createComponent(OrderTotalComponent); fixture.componentRef.setInput('amount', 1234.5); await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('£1,234.50'); });});Three things worth noticing, because they are the modern shape:
- Standalone components go in
imports, notdeclarations.declarationsis the NgModule-era API. setInput()oncomponentRef, not assignment to a component property — that is what drives signal inputs correctly.await fixture.whenStable()rather than a baredetectChanges(). More on that under zoneless.
TestBed and configuring the module
Section titled “TestBed and configuring the module”TestBed builds a miniature Angular environment for the test. The configuration you give it is your test’s dependency graph, so keep it small.
await TestBed.configureTestingModule({ imports: [OrderListComponent], providers: [ provideHttpClient(), provideHttpClientTesting(), provideRouter([]), { provide: OrderApiClient, useClass: FakeOrderApiClient }, ],}).compileComponents();Global providers. The CLI’s providersFile option lets you supply providers to every test rather than repeating them:
import { EnvironmentProviders, Provider } from '@angular/core';import { provideHttpClientTesting } from '@angular/common/http/testing';
const testProviders: (Provider | EnvironmentProviders)[] = [provideHttpClientTesting()];export default testProviders;Point angular.json → test.providersFile at it. Useful — but resist putting everything there. Providers that are invisible in the spec file make tests hard to read and easy to break accidentally.
Other angular.json test options worth knowing: include / exclude globs, setupFiles for polyfills and global mocks, coverage, and browsers for real-browser runs.
Testing components
Section titled “Testing components”Rendering and DOM interaction
Section titled “Rendering and DOM interaction”it('emits when the user confirms', async () => { const fixture = TestBed.createComponent(ConfirmDialogComponent); await fixture.whenStable();
const emitted: string[] = []; fixture.componentInstance.confirmed.subscribe(v => emitted.push(v));
const button: HTMLButtonElement = fixture.nativeElement.querySelector('[data-testid="confirm"]'); button.click(); await fixture.whenStable();
expect(emitted).toEqual(['confirmed']);});Query by intent, not by structure. [data-testid] or an accessible role survives markup changes; div > div:nth-child(2) span does not.
// Brittle — breaks when a wrapper div is addedfixture.nativeElement.querySelector('.card > .body > p');
// Durable — breaks only if the meaning changesfixture.nativeElement.querySelector('[data-testid="order-status"]');harness.getHarness(MatButtonHarness.with({ text: 'Save' }));Signals in component tests
Section titled “Signals in component tests”Signal state needs no special handling — read it like any signal, but let the fixture settle before asserting on rendered output:
it('recomputes the total when quantity changes', async () => { const fixture = TestBed.createComponent(CartComponent); const cart = fixture.componentInstance; await fixture.whenStable();
cart.quantity.set(3); // writable signal await fixture.whenStable(); // let the effect/render run
expect(cart.total()).toBe(29.97); // computed signal expect(fixture.nativeElement.textContent).toContain('29.97'); // rendered});For signal inputs, always drive them through setInput:
fixture.componentRef.setInput('order', { id: 'A-1', total: 10 });await fixture.whenStable();Assigning fixture.componentInstance.order = … bypasses the input machinery and will not behave like a real binding.
Testing services
Section titled “Testing services”Services are the easiest thing to test well, because they have no DOM.
describe('PricingService', () => { let service: PricingService;
beforeEach(() => { TestBed.configureTestingModule({ providers: [ PricingService, { provide: TaxRateProvider, useValue: { rate: () => 0.2 } }, ], }); service = TestBed.inject(PricingService); });
it('applies tax to the net amount', () => { expect(service.gross(100)).toBe(120); });});Prefer fakes to mocks. A small hand-written FakeOrderApiClient that behaves like the real thing produces tests that read as scenarios. A pile of vi.fn() spies with mockReturnValue produces tests that read as wiring diagrams and break on every refactor.
Use a spy when the call itself is the behaviour under test — “submitting sends exactly one request” — not as the default.
Testing HttpClient
Section titled “Testing HttpClient”Never let a unit test make a real network call. provideHttpClientTesting intercepts requests and lets you assert on them.
import { provideHttpClient } from '@angular/common/http';import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
describe('OrderApiClient', () => { let api: OrderApiClient; let http: HttpTestingController;
beforeEach(() => { TestBed.configureTestingModule({ providers: [OrderApiClient, provideHttpClient(), provideHttpClientTesting()], }); api = TestBed.inject(OrderApiClient); http = TestBed.inject(HttpTestingController); });
afterEach(() => http.verify()); // fails the test on unexpected/outstanding requests
it('requests the order and maps the response', () => { let result: Order | undefined; api.getOrder('A-1').subscribe(o => (result = o));
const req = http.expectOne('/api/orders/A-1'); expect(req.request.method).toBe('GET'); req.flush({ id: 'A-1', total_pence: 1050 });
expect(result).toEqual({ id: 'A-1', total: 10.5 }); });
it('surfaces a friendly error on 500', () => { let error: Error | undefined; api.getOrder('A-1').subscribe({ error: e => (error = e) });
http.expectOne('/api/orders/A-1') .flush('boom', { status: 500, statusText: 'Server Error' });
expect(error?.message).toContain('Could not load order'); });});http.verify() in afterEach is the line people omit and then wonder why a leaked request from one spec breaks another.
Testing the router
Section titled “Testing the router”Test what the user reaches, not that router.navigate was called. RouterTestingHarness drives real navigation against a test route table and renders the routed component, so the assertion is about the screen the user ends up on.
The examples below use this guard and these two stand-in pages:
import { inject } from '@angular/core';import { CanActivateFn, Router } from '@angular/router';import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (_route, state) => { const auth = inject(AuthService); const router = inject(Router); return auth.isLoggedIn() ? true : router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });};Behaviour-level: navigate and check where you land
Section titled “Behaviour-level: navigate and check where you land”import { Component } from '@angular/core';import { TestBed } from '@angular/core/testing';import { provideRouter, Router } from '@angular/router';import { RouterTestingHarness } from '@angular/router/testing';import { describe, expect, it } from 'vitest';import { authGuard } from './auth.guard';import { AuthService } from './auth.service';
@Component({ template: '<h1>Orders</h1>' })class OrdersPage {}
@Component({ template: '<h1>Sign in</h1>' })class LoginPage {}
async function setup(isLoggedIn: boolean) { TestBed.configureTestingModule({ providers: [ { provide: AuthService, useValue: { isLoggedIn: () => isLoggedIn } }, provideRouter([ { path: 'orders', component: OrdersPage, canActivate: [authGuard] }, { path: 'login', component: LoginPage }, ]), ], }); return RouterTestingHarness.create();}
describe('authGuard', () => { it('lets a signed-in user reach /orders', async () => { const harness = await setup(true); await harness.navigateByUrl('/orders', OrdersPage);
expect(harness.routeNativeElement?.textContent).toContain('Orders'); expect(TestBed.inject(Router).url).toBe('/orders'); });
it('sends an anonymous user to /login with a returnUrl', async () => { const harness = await setup(false); await harness.navigateByUrl('/orders', LoginPage);
expect(harness.routeNativeElement?.textContent).toContain('Sign in'); expect(TestBed.inject(Router).url).toBe('/login?returnUrl=%2Forders'); });});navigateByUrl(url, ComponentType) also asserts that the routed component is of the type you name, so a guard that sends the user to the wrong page fails loudly.
Unit-level: call the guard as a function
Section titled “Unit-level: call the guard as a function”Guards and resolvers are plain functions now. For branch-by-branch checks, call them inside an injection context and assert on the return value. The test still provides the router, because the guard injects Router to build its redirect:
import { TestBed } from '@angular/core/testing';import { ActivatedRouteSnapshot, provideRouter, Router, RouterStateSnapshot, UrlTree,} from '@angular/router';import { describe, expect, it } from 'vitest';import { authGuard } from './auth.guard';import { AuthService } from './auth.service';
function runGuard(isLoggedIn: boolean, url = '/orders') { TestBed.configureTestingModule({ providers: [ provideRouter([]), { provide: AuthService, useValue: { isLoggedIn: () => isLoggedIn } }, ], }); const route = {} as ActivatedRouteSnapshot; // the guard ignores it const state = { url } as RouterStateSnapshot; // only `url` is read return TestBed.runInInjectionContext(() => authGuard(route, state));}
describe('authGuard (unit)', () => { it('allows a signed-in user', () => { expect(runGuard(true)).toBe(true); });
it('returns a redirect to /login for an anonymous user', () => { const result = runGuard(false) as UrlTree; const router = TestBed.inject(Router);
expect(result).toBeInstanceOf(UrlTree); expect(router.serializeUrl(result)).toBe('/login?returnUrl=%2Forders'); });});Partial snapshot objects are acceptable here only because the guard reads nothing but state.url; if a guard reads route params, build them with convertToParamMap instead.
A reminder that belongs in every routing test file: a guard is not an authorization boundary. It controls navigation in a client the user fully controls. See Security.
Testing forms
Section titled “Testing forms”Assert on form state and rendered errors, not on internal validator wiring.
it('blocks submission until the email is valid', async () => { const fixture = TestBed.createComponent(SignupFormComponent); await fixture.whenStable(); const form = fixture.componentInstance.form;
form.controls.email.setValue('not-an-email'); form.controls.email.markAsTouched(); await fixture.whenStable();
expect(form.valid).toBe(false); expect(fixture.nativeElement.textContent).toContain('Enter a valid email');
const submit: HTMLButtonElement = fixture.nativeElement.querySelector('[data-testid="submit"]'); expect(submit.disabled).toBe(true);});Async validators need the fixture to settle — await fixture.whenStable() after setting the value, or the pending state will still be in flight when you assert.
Async testing, timers, and stability
Section titled “Async testing, timers, and stability”This is where suites become flaky.
Prefer await fixture.whenStable(). It waits for Angular to finish its pending work and is the most robust default.
For time-dependent code, use fake timers rather than real waits:
it('debounces the search request', async () => { vi.useFakeTimers();
component.searchTerm.set('ord'); vi.advanceTimersByTime(299); http.expectNone('/api/search?q=ord'); // not yet
vi.advanceTimersByTime(1); http.expectOne('/api/search?q=ord'); // now
vi.useRealTimers();});Never setTimeout in a test to “wait for things to settle”. It is a race you will lose on a slow CI machine, and it is the single most common source of flakiness.
fakeAsync, flush, and zone.js
Section titled “fakeAsync, flush, and zone.js”fakeAsync, flush, and waitForAsync are zone.js APIs. On the Vitest baseline they require adding zone.js/plugins/vitest-patch to your test polyfills.
Angular’s own guidance is explicit: that patch is a bridge for existing suites, and teams should plan to convert to native async/await plus Vitest fake timers, which is the established approach going forward. Treat fakeAsync as legacy in new code.
Testing under zoneless
Section titled “Testing under zoneless”Zoneless is the default from Angular 21, and it changes test ergonomics in a way that trips people up.
Under zone.js, fixture.detectChanges() was the workhorse because the zone told Angular something happened. Without zones, Angular is notified by signals and explicit APIs instead.
The practical rule: prefer await fixture.whenStable() over fixture.detectChanges(). whenStable() waits for Angular’s scheduled work to complete; detectChanges() forces a synchronous pass that may not reflect what the real application would do.
// Fragile under zoneless — forces a pass that may not match runtime behaviourcomponent.items.set([...]);fixture.detectChanges();
// Robust — lets Angular schedule and settle exactly as it would in the appcomponent.items.set([...]);await fixture.whenStable();If a test passes with detectChanges() but fails with whenStable(), that usually means the component relies on a change-detection pass the real app would not perform — a bug, not a test problem.
See Change Detection and Zoneless Angular for the underlying model.
Component harnesses
Section titled “Component harnesses”For component libraries and any widget used across many specs, harnesses give you a stable API instead of DOM selectors:
const loader = TestbedHarnessEnvironment.loader(fixture);const button = await loader.getHarness(MatButtonHarness.with({ text: 'Save' }));await button.click();The value is decoupling: when the widget’s internal markup changes, the harness absorbs it and your specs do not. Writing your own harness is worth it for a component used in more than a handful of tests.
Test strategy: the shape that works
Section titled “Test strategy: the shape that works”| Layer | Proportion | What it proves | Cost |
|---|---|---|---|
| Unit (services, pipes, pure functions) | Many | Logic is correct | Cheap, fast |
| Component (rendered, with fakes) | Many | The UI reflects state and reacts to input | Moderate |
| Integration (a feature, real collaborators, faked HTTP) | Some | The pieces work together | Slower, high value |
| E2E (real browser, real backend or contract fake) | Few | Critical journeys work end to end | Slowest, most brittle |
Integration tests are the underrated tier. Rendering a feature with real child components, a real router, and a faked HTTP layer catches the wiring bugs that unit tests miss and E2E tests find far too slowly.
E2E should be a thin layer over critical journeys only — login, checkout, the thing that loses money when broken. The tooling matters less than the discipline of keeping the layer small.
Common mistakes and anti-patterns
Section titled “Common mistakes and anti-patterns”Anti-pattern: asserting on spies instead of outcomes
Section titled “Anti-pattern: asserting on spies instead of outcomes”// BAD — passes even if the UI is completely brokenit('loads orders', () => { const spy = vi.spyOn(service, 'loadOrders'); component.ngOnInit(); expect(spy).toHaveBeenCalled();});// BETTER — fails if the user cannot see their ordersit('shows the orders once loaded', async () => { const fixture = TestBed.createComponent(OrderListComponent); await fixture.whenStable(); http.expectOne('/api/orders').flush([{ id: 'A-1', total: 10 }]); await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('A-1');});Anti-pattern: one giant beforeEach
Section titled “Anti-pattern: one giant beforeEach”A beforeEach that builds every possible dependency makes each spec depend on setup it does not use, and a change to one scenario breaks unrelated tests. Prefer small builders:
function renderOrderList(overrides: Partial<Options> = {}) { /* … */ }
it('shows an empty state', async () => { const { fixture } = await renderOrderList({ orders: [] }); expect(fixture.nativeElement.textContent).toContain('No orders yet');});Other frequent mistakes
Section titled “Other frequent mistakes”- Testing framework behaviour rather than your own.
setTimeoutwaits instead of fake timers orwhenStable().- Forgetting
http.verify(), so leaked requests corrupt later specs. - Assigning inputs directly instead of
componentRef.setInput(). - Chasing 100% coverage — coverage measures lines executed, not assertions made. A suite can hit 100% and assert nothing.
- Shared mutable state between specs (a module-level array, a stubbed singleton) — the classic source of “passes alone, fails in the suite”.
Failure modes and debugging
Section titled “Failure modes and debugging”| Symptom | Likely cause | Action |
|---|---|---|
| Passes alone, fails in suite | Shared mutable state, or a leaked HTTP request/subscription | Add http.verify(); reset state in beforeEach; run with --sequence.shuffle to expose order dependence |
| Passes locally, fails on CI | Real timing dependency | Replace waits with fake timers and whenStable() |
Passes with detectChanges(), fails with whenStable() |
Component depends on a CD pass the app would not do | Fix the component, not the test |
NullInjectorError: No provider for X |
Missing provider in TestBed |
Add it, or supply a fake — do not import the whole app module |
| Signal input is undefined | Assigned directly instead of setInput |
Use fixture.componentRef.setInput() |
| Test hangs | Awaiting a promise that never resolves, or fake timers never advanced | Advance timers; check for an un-flushed HTTP request |
Debugging technique that saves the most time: run the single failing spec in isolation with it.only, then re-run the whole file with shuffling. If it only fails in the suite, it is state leakage, not logic.
Performance: keeping a large suite fast
Section titled “Performance: keeping a large suite fast”Suites die when a full run stops fitting in a coffee break.
jsdomover a real browser for the default run. Reservebrowsersmode for the small set of specs that genuinely need real layout or real browser APIs.- Keep
TestBedconfiguration minimal. Compiling components is the expensive part; importing a barrel file that pulls in half the app multiplies it. - Shard on CI. Split the suite across parallel jobs; Vitest supports this natively. It is the single biggest lever once you are past a few thousand tests.
- Watch mode locally, single run on CI — the CLI already does this for you.
- Delete tests that assert nothing. A suite is not an asset by weight.
Measure before optimising: run with reporting on to find the slowest files, and expect a small number of specs to dominate.
Accessibility testing
Section titled “Accessibility testing”Automated checks catch a real but limited slice — missing labels, bad contrast, invalid ARIA. They cannot tell you whether the experience makes sense.
- Query by role and accessible name in component tests; it asserts accessibility and resists refactors at the same time.
- Add an automated a11y assertion to key rendered states.
- Keyboard-navigate the real feature manually. Nothing automated replaces this.
- Angular Aria (
@angular/aria) provides headless directives implementing WAI-ARIA patterns with keyboard and focus handling already correct — using them removes a whole class of accessibility defects rather than testing for them after the fact.
Migrating an existing suite
Section titled “Migrating an existing suite”From Karma to Vitest, Angular provides both a documented manual path and an automated schematic:
ng g @schematics/angular:refactor-jasmine-vitestThe schematic converts fit/fdescribe → it.only/describe.only, xit/xdescribe → .skip, spyOn → vi.spyOn, jasmine.createSpy → vi.fn, jasmine.any/objectContaining → the expect equivalents, and adds TODO comments where it cannot convert.
Know its limits — this is documented as experimental. It does not:
- install
vitestor related dependencies; - change
angular.jsonto the Vitest builder, or migratepolyfills/stylesfrom thetesttarget; - remove
karma.conf.jsortest.ts; - handle complex or nested spy scenarios.
So the realistic sequence is: install dependencies and update angular.json yourself, run the schematic, then review every file it touched — paying attention to intricate spies. Migrate a directory at a time behind a green build rather than converting 3,000 specs in one commit.
Maintaining tests through version upgrades is mostly a matter of not coupling to internals. Suites that assert on rendered behaviour survive major upgrades; suites that assert on private methods and spy call counts are the reason teams get stuck three majors behind.
Using AI assistants to write tests
Section titled “Using AI assistants to write tests”Worth addressing directly, because it is now how a lot of test code gets written.
Where it genuinely helps: generating the boilerplate around a TestBed setup, enumerating edge cases you had not considered, and converting a suite mechanically between frameworks.
Where it costs you:
- False confidence. Generated tests frequently assert that the code does what it currently does — including its bugs. A test written from the implementation cannot detect that the implementation is wrong.
- Brittle assertions. Assistants reach for spies and structural selectors, which is exactly the coupling that makes suites expensive.
- Volume over value. Twenty generated specs covering one branch each is worse than three that cover the real scenarios, and it inflates coverage while lowering confidence.
- Duplication. Generated specs often re-test what an existing spec already covers.
- Security and privacy. Never paste production data, credentials, tokens, or customer records into a prompt to make a fixture “realistic”. Use synthetic data.
The rule: every generated test gets reviewed as if a junior wrote it. Ask what behaviour it protects, whether it would fail if the feature broke, and whether it would survive a rename. If the answer to any of those is unsatisfying, delete it — an unreviewed generated suite is a maintenance liability that looks like an asset.
Trade-offs and alternatives
Section titled “Trade-offs and alternatives”| Decision | Option A | Option B | Choose A when |
|---|---|---|---|
| Runner | Vitest (default) | Karma/Jasmine | Anything new — Karma is legacy |
| DOM | jsdom |
Real browser (browsers) |
Default; use a browser only for layout/real-API needs |
| Doubles | Hand-written fakes | Spies/mocks | Almost always — spies only when the call is the behaviour |
| Selectors | data-testid / role |
CSS structure | Always |
| Async | whenStable() + fake timers |
fakeAsync/flush |
New code — fakeAsync is zone-era |
| Depth | Integration tests | Many isolated unit tests | The value is in the wiring |
Senior interview scenarios
Section titled “Senior interview scenarios”Q: How do you make a 10,000-test suite maintainable and fast?
Maintainability first: assert on rendered behaviour and public API, never on spies or private methods, so refactors do not cascade. Then speed: keep TestBed configuration minimal (compilation dominates), stay on jsdom except where a real browser is genuinely needed, and shard across parallel CI jobs. Finally, prune — measure the slowest files, and delete specs that assert nothing. Volume is not coverage.
Q: How do you test HTTP, router, and forms without brittle implementation coupling?
HTTP: provideHttpClientTesting, assert on the request that went out and the state that resulted, with http.verify() to catch leaks — not on whether a service method was called. Router: RouterTestingHarness and assert on the resulting URL or rendered component, not on router.navigate spies; guards are plain functions, so call them in an injection context and assert the return. Forms: assert form validity and the rendered error message, not validator internals.
Q: A test passes with detectChanges() but fails with whenStable(). What does that tell you?
Usually that the component depends on a change-detection pass the real application would not perform — under zoneless, nothing forces that pass. detectChanges() is masking a missing notification: state changed in a way Angular was never told about, typically a plain property mutated where a signal was needed. Fix the component.
Q: Your suite is flaky on CI but green locally. How do you diagnose it?
Assume timing or shared state. Replace any real waits with fake timers and whenStable(). Add http.verify() to catch leaked requests. Run with shuffling to expose order dependence — if it only fails in a suite, some module-level or stubbed-singleton state is surviving between specs. Reproduce with the CI’s parallelism locally before “fixing” anything.
Q: When do you write an E2E test instead of an integration test? When the risk lives in something only a real browser and a real backend can exercise — actual navigation, real auth redirects, cross-origin behaviour, or a journey whose failure costs money. Everything else belongs one tier down, where it runs in seconds and fails with a useful message. E2E is a thin layer over critical journeys, not a second copy of the suite.
Q: How do you decide what not to test? Anything the framework or a third party already guarantees, trivial pass-through code, and private methods. The budget saved goes into integration tests. The test to write is the one that would fail if the feature broke and pass through any refactor that keeps the behaviour — anything else is costing more than it protects.
Related pages
Section titled “Related pages”- Change Detection and Zoneless Angular
- Signals and Angular Reactivity
- HttpClient and API Integration
- Routing in Depth
- Angular Security
- Angular Modernization and Version Upgrades