Angular · Lesson 7
Testing & architecture
Testing Angular code with TestBed, component harnesses, HttpTestingController, fake time and signals, and structuring an app so it stays testable: feature folders, smart and presentational components, state in signal-based services, when to reach for NgRx, and sharing code in an Nx monorepo.
In short
TestBedgives each test its own injector and fakesHttpTestingController:expectOne,flush,verifysetInput, thenawait fixture.whenStable()- Smart pages, presentational UI, state in signal stores
- Feature folders and Nx boundaries keep it that way
Testing and architecture are one topic wearing two hats. Code that is well structured (small presentational components, state in services, data access behind an interface) is easy to test, and code that is hard to test is usually telling you something about its structure. Interviewers ask about both together: "How would you test this component?" quickly becomes "Why does this component make HTTP calls?"
The first half is the testing toolbox: TestBed, harnesses, HttpTestingController, fake time, signals. The
second half is how Angular codebases are organised, from one feature folder up to an Nx monorepo with many teams.
Snippets that need Angular have no Try button; the exercises rebuild each tool in plain TypeScript.
The test runner
New Angular projects use Vitest by default (since Angular 21; it was experimental in 20). Older ones use Karma
with Jasmine, or Jest. The Angular parts
(TestBed, harnesses, HttpTestingController) are the same everywhere; only describe/it/expect and the mocking
helpers (vi.fn(), jasmine.createSpy(), jest.fn()) differ.
TestBed: a small Angular app per test
TestBed builds an injector (and, for components, a host to render into) for each test. You give it providers, and
replace the ones you don't want to run for real:
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs';
import { OrderApi } from './order-api';
describe('OrderApi', () => {
let api: OrderApi;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
api = TestBed.inject(OrderApi);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify()); // fails if the code sent a request that no test matched
it('loads an order', async () => {
const order = firstValueFrom(api.get('7')); // subscribing sends the request
const req = http.expectOne('/api/orders/7');
expect(req.request.method).toBe('GET');
req.flush({ id: '7', total: 120 });
expect(await order).toEqual({ id: '7', total: 120 });
});
it('maps a 404', async () => {
const order = firstValueFrom(api.get('nope'));
http.expectOne('/api/orders/nope').flush({ title: 'Not Found' }, { status: 404, statusText: 'Not Found' });
await expect(order).rejects.toMatchObject({ status: 404 });
});
});
Components get a fixture. Set inputs through componentRef.setInput (signal inputs are read-only from outside), then
let Angular render. In a zoneless app (the default since Angular 21), await fixture.whenStable() does that. With
zone.js, call fixture.detectChanges() (or fixture.autoDetectChanges() once) instead:
import { TestBed } from '@angular/core/testing';
import { OrderCard } from './order-card';
import { OrderApi } from './order-api';
it('shows the order number and total', async () => {
TestBed.configureTestingModule({ providers: [{ provide: OrderApi, useValue: { cancel: vi.fn() } }] });
const fixture = TestBed.createComponent(OrderCard);
fixture.componentRef.setInput('order', { id: '7', number: 'A-1007', total: 120 });
await fixture.whenStable(); // zoneless: change detection runs, then the promise resolves
const text = fixture.nativeElement.textContent;
expect(text).toContain('A-1007');
expect(text).toContain('120');
});
- Replace dependencies with providers:
{ provide: OrderApi, useValue: fake }oruseClass: FakeOrderApi. That's dependency injection paying off. (Exercise 1 builds a typed spy for such fakes.) - Functional guards, resolvers and interceptors need an injection context:
TestBed.runInInjectionContext(() => authGuard(route, state)). - Routing:
RouterTestingHarnessnavigates for real:const harness = await RouterTestingHarness.create(); const page = await harness.navigateByUrl('/orders/7', OrderPage);. - HTTP: never fake
HttpClientby hand.provideHttpClientTesting()sends every request to a testing backend that the test answers withexpectOne(...).flush(...), and interceptors you register withprovideHttpClient(withInterceptors([...]))still run. (Exercise 3 builds it.)
Testing signals
Signals are synchronous values, which makes most signal code easy to test: call methods, read signals.
import { TestBed } from '@angular/core/testing';
import { TodoStore } from './todo-store';
it('counts what is left to do', () => {
const store = TestBed.inject(TodoStore);
store.add('Buy milk');
store.add('Send report');
store.toggle(store.todos()[0].id);
expect(store.remaining()).toBe(1); // computed: recalculated on read
});
it('saves to localStorage in an effect', () => {
const store = TestBed.inject(TodoStore);
store.add('Buy milk');
TestBed.tick(); // effects run later, not on set(); this runs them now (Angular 19: TestBed.flushEffects())
expect(localStorage.getItem('todos')).toContain('Buy milk');
});
computedis lazy and synchronous: reading it after a change gives the new value.effectruns later (as part of change detection), so flush it withTestBed.tick()orawait fixture.whenStable().- For components, set signal inputs with
setInput, thenawait fixture.whenStable().
Component harnesses
A harness is a test API for a component: getValue(), increment(), isDisabled(). The test talks to the
harness, and only the harness knows the component's DOM. When the template changes, you fix one harness instead of
fifty tests. Angular Material ships harnesses for all its components, and the CDK lets you write your own:
import { ComponentHarness } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatButtonHarness } from '@angular/material/button/testing';
export class QuantityPickerHarness extends ComponentHarness {
static hostSelector = 'app-quantity-picker';
private readonly plus = this.locatorFor('button.plus');
private readonly value = this.locatorFor('.value');
async increment(): Promise<void> {
await (await this.plus()).click();
}
async getValue(): Promise<number> {
return Number(await (await this.value()).text());
}
}
// In a test:
// const loader = TestbedHarnessEnvironment.loader(fixture);
// const picker = await loader.getHarness(QuantityPickerHarness);
// await picker.increment();
// expect(await picker.getValue()).toBe(2);
// const save = await loader.getHarness(MatButtonHarness.with({ text: 'Save' }));
// expect(await save.isDisabled()).toBe(false);
Harness methods are async and wait for the component to be stable (change detection done, pending work finished)
before reading, which removes most timing flakiness from component tests.
Time: fake timers and marble tests
Code with timers (debounce, polling, retries, toasts) shouldn't make tests wait. Three tools:
fakeAsync+tick(ms)/flush()(Angular, needs zone.js). Since Angular 19 (zone.js 0.15), timers still queued when the test ends are flushed for you. WithfakeAsync(fn, { flush: false })(the old default), the test fails instead ("1 periodic timer(s) still in the queue."), which catches polling nobody stopped.discardPeriodicTasks()drops intervals you expect.vi.useFakeTimers()(Vitest, works zoneless):vi.advanceTimersByTime(ms),vi.runAllTimers(), and the...Asyncvariants when promises are involved.- Marble tests (
TestScheduler.run) for RxJS pipelines: deterministic, exact, and virtual. (See the RxJS topic.)
import { debounceTime, distinctUntilChanged, map } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
const scheduler = new TestScheduler((actual, expected) =>
console.log(JSON.stringify(actual) === JSON.stringify(expected) ? 'pass' : `fail, got ${JSON.stringify(actual)}`),
);
scheduler.run(({ cold, expectObservable }) => {
// 'an' at 0 ms, 'ang' at 51 ms, 'angular ' at 452 ms, then the input completes
const typed = cold('a 50ms b 400ms c|', { a: 'an', b: 'ang', c: 'angular ' });
const query$ = typed.pipe(debounceTime(300), map((q) => q.trim()), distinctUntilChanged());
expectObservable(query$).toBe('351ms b 101ms (c|)', { b: 'ang', c: 'angular' });
});
console.log('virtual time: the 300 ms debounce took no real time');
Exercise 5 builds a fake clock with fakeAsync's rules.
What to test, and how much
- Services and stores: plain unit tests. Fast, no DOM, most of your logic should live here.
- Presentational components: inputs in, DOM or outputs out. A harness keeps them robust.
- Smart components: a few tests with faked services (or
HttpTestingController), checking what the user sees. - End to end (Playwright): the critical journeys (sign in, checkout), against a real or seeded backend.
- Assert on results (what's shown, what's returned, which request was sent), not on private methods or how many times an internal helper was called. Over-mocked tests pass while the app is broken.
Architecture: organise by feature
Group code by feature, not by kind. A components/ and a services/ folder at the top level means every change
touches both, and nothing tells you what belongs together:
src/app/
app.config.ts, app.routes.ts
core/ interceptors, guards, ErrorHandler, auth: things the whole app uses once
shared/ui/ presentational building blocks: buttons, cards, form fields
orders/
orders.routes.ts lazy-loaded from app.routes.ts
data-access/ order-api.ts, order-store.ts (state and API, no components)
feature/ order-list-page.ts, order-page.ts (smart: inject, coordinate)
ui/ order-card.ts, order-status-badge.ts (presentational: input/output only)
billing/
...
Each feature is lazy-loaded, owns its state, and exposes as little as possible to the rest of the app.
Smart and presentational components
- Presentational (dumb) components get everything through
input()and report everything throughoutput(). No injected services, no HTTP. They'reOnPush, reusable, and trivial to test. - Smart (container) components inject stores and services, and pass data down. Usually one per route.
import { ChangeDetectionStrategy, Component, inject, input, output } from '@angular/core';
import { Order, OrderStore } from '../data-access/order-store';
@Component({
selector: 'app-order-card',
changeDetection: ChangeDetectionStrategy.OnPush, // the default since Angular 22; spell it out on older versions
template: `
<h3>{{ order().number }}</h3>
<button (click)="cancel.emit(order().id)" [disabled]="order().status !== 'open'">Cancel</button>
`,
})
export class OrderCard {
readonly order = input.required<Order>();
readonly cancel = output<string>();
}
@Component({
selector: 'app-order-list-page',
imports: [OrderCard],
template: `
@for (order of store.visible(); track order.id) {
<app-order-card [order]="order" (cancel)="store.cancel($event)" />
}
`,
})
export class OrderListPage {
protected readonly store = inject(OrderStore);
}
State in services with signals
Most features need nothing more than a store service: private writable signals, read-only signals exposed with
asReadonly(), computed for derived values, and methods for every change (exercise 4 builds one, with optimistic
updates). @Injectable({ providedIn: 'root' }) (or @Service(), its shorter form since Angular 22) makes it
app-wide; listing it in a component's providers gives each component instance its own store that dies with it (a
wizard, an editor tab).
Rules that keep it healthy:
- One owner per piece of state. Components read, the store's methods write.
- Derive, don't copy:
computedinstead of a second signal you keep in sync. - Update immutably (new arrays and objects), so
OnPush,@fortracking and signal equality see the change. - Keep RxJS for events and async flows (HTTP, debounce, websockets) and signals for state; bridge with
toSignal.
When to use NgRx
| Service with signals | NgRx SignalStore | NgRx Store (classic) | |
|---|---|---|---|
| what it is | your own class | a function that builds a store from features | actions, reducers, effects, selectors |
| boilerplate | lowest | low | high |
| structure | whatever you write | withState, withComputed, withMethods, withHooks | strict: every change is an action |
| shared extras | none | entities, rxMethod, custom features, DevTools via add-ons | DevTools time travel, effects, router store |
| good for | most features | features with lots of state, shared conventions across teams | big apps with many teams, complex cross-feature events, audit trails |
import { computed } from '@angular/core';
import { patchState, signalStore, withComputed, withMethods, withState } from '@ngrx/signals';
import { Filter, Todo } from './todo';
export const TodoStore = signalStore(
{ providedIn: 'root' },
withState({ todos: [] as Todo[], filter: 'all' as Filter }),
withComputed(({ todos }) => ({
remaining: computed(() => todos().filter((t) => !t.done).length),
})),
withMethods((store) => ({
setFilter(filter: Filter) {
patchState(store, { filter });
},
})),
);
A good default: start with services, move a feature to SignalStore when its store grows or several teams need the same conventions, and choose the classic store deliberately (event-driven flows across features, strong traceability), not by habit. Mixing approaches inside one feature is the expensive option.
Sharing code in a monorepo (Nx)
When several apps (a shop, a back office, an admin portal) share code, an Nx workspace keeps them in one repo as many small libraries:
- Libraries are tagged by type (
feature,ui,data-access,util) and scope (orders,billing,shared). The@nx/enforce-module-boundarieslint rule turns "ui must not fetch data" and "billing must not reach into orders" into build errors. (Exercise 2.) - Libraries are imported through path aliases (
@shop/orders/data-access), never through relative paths into another library's folder. Each library'sindex.tsis its public API. nx graphdraws the project graph, and circular dependencies are lint errors.nx affected -t lint test buildruns targets only for projects touched by a change and everything that depends on them, which keeps CI fast. (Exercise 6.)- Generators (
nx g @nx/angular:library ...) create libraries with the same structure every time.
Without Nx, an Angular CLI workspace with several projects, or published npm packages, can share code too, but you
lose the graph-aware tooling.
Common mistakes
- Tests that test Angular itself (that an
@Inputreceives a value) instead of your behaviour. - Mocking
HttpClientby hand instead of usingprovideHttpClientTesting(). - Forgetting
http.verify(), so duplicate or stray requests go unnoticed. - Assigning to a signal input in a test instead of
fixture.componentRef.setInput(...). - Expecting an
effectto have run right afterset(). - Querying deep DOM structure in every test instead of using a harness.
- Real timers in tests (
await sleep(500)): slow and flaky. Use fake timers or marbles. - Components that inject
HttpClientdirectly. Put calls in a data-access service or store. - One giant
sharedlibrary that everything imports, so every change affects everything. - Reaching for the classic NgRx store for a feature that a 40-line service would handle.
The exercises
- Build a test spy: a typed
createSpywithcalls,returnValue,callFakeandreset. - Library import rules: Nx-style type and scope tags for one import.
- Build HttpTestingController: requests on subscribe,
expectOne,flush, cancellation andverify. - A signal-based store service: read-only signals,
computed, latest-wins loading, optimistic updates with rollback. - A fake clock for fakeAsync-style tests:
tick,flush, microtasks, intervals and leftover-timer checks. - Check a monorepo's boundaries, cycles and affected projects: the project graph, three-colour DFS and
nx affected.
Practise this lesson
In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app