Test the code behind your components. This part tests a store, a service that calls a server, a component that loads with httpResource, a route guard and routed pages, with no real server and no browser.
Part 24 tested components: what they show and what happens when you click. Most of an app’s logic doesn’t live in components, though. It lives in stores, in services that talk to a server, and in the router’s guards. Those are the parts we test here.
This part covers testing a store with TestBed.inject, testing HTTP code with HttpTestingController, testing a component that loads with httpResource, testing a guard with TestBed.runInInjectionContext, and testing routes with RouterTestingHarness. The code under test comes from Part 15 (stores), Part 16 and Part 17 (routes and guards), Part 18 (HttpClient) and Part 19 (httpResource). Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3, and each test run with ng test, before this was published.
Try this first
Here’s the counter store from Part 15, a page that uses it, and a test file for the store. Paste all three:
// src/app/counter-store.ts
import { Service, computed, signal } from '@angular/core';
@Service()
export class CounterStore {
private readonly countState = signal(0);
readonly count = this.countState.asReadonly();
readonly isBig = computed(() => this.count() >= 3);
increment() {
this.countState.update((n) => n + 1);
}
reset() {
this.countState.set(0);
}
}
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { CounterStore } from './counter-store';
@Component({
selector: 'app-root',
template: `
<p>Count: {{ store.count() }}</p>
<button (click)="store.increment()">Add one</button>
`,
})
export class App {
protected readonly store = inject(CounterStore);
}
// src/app/counter-store.spec.ts
import { TestBed } from '@angular/core/testing';
import { CounterStore } from './counter-store';
describe('CounterStore', () => {
it('adds one', () => {
const store = TestBed.inject(CounterStore);
store.increment();
expect(store.count()).toBe(1);
});
it('adds one again', () => {
const store = TestBed.inject(CounterStore);
store.increment();
expect(store.count()).toBe(1);
});
});
@Service() makes one store for the whole app. Both tests call increment() once. Before you read on, guess: does the second test see 1 or 2? Then run ng test --watch=false.
Both pass. The end of the output says:
Test Files 1 passed (1)
Tests 2 passed (2)
“One store for the whole app” is still true. But in tests, each test gets a whole new app. TestBed builds a fresh injector, the object that creates and holds services (Part 13), for every test, and throws it away afterwards. So the second test gets a new CounterStore that starts at 0. Tests can’t leak state into each other, and you can run them in any order.
The app itself works as before. In ng serve, click Add one, and the page shows:
Count: 1
Add one
A quick recap of Part 24: ng test runs every *.spec.ts file with Vitest, in a fake browser page called jsdom. describe groups tests, it is one test, and expect(...).toBe(...) checks a value. TestBed is Angular’s test version of an app: TestBed.configureTestingModule({ providers: [...] }) sets it up, and TestBed.createComponent gives you a fixture to look at. Here we use one more method, TestBed.inject(SomeService), which is inject() for a test. It asks the test’s injector for the service.
Testing a store: read the signals
A store from Part 15 has no template. Its public face is a few signals and a few methods. So a store test does the same thing a component does: call an action, then read a signal.
Here’s the todo store from Part 15 again, and a test for it:
// src/app/todo-store.ts
import { Service, computed, signal } from '@angular/core';
export interface Todo {
id: number;
text: string;
done: boolean;
}
export type Filter = 'all' | 'active' | 'done';
interface TodoState {
todos: Todo[];
filter: Filter;
}
@Service()
export class TodoStore {
private readonly state = signal<TodoState>({
todos: [
{ id: 1, text: 'Buy milk', done: false },
{ id: 2, text: 'Call Ana', done: true },
],
filter: 'all',
});
private nextId = 3;
readonly todos = computed(() => this.state().todos);
readonly visible = computed(() => {
const { todos, filter } = this.state();
if (filter === 'active') return todos.filter((t) => !t.done);
if (filter === 'done') return todos.filter((t) => t.done);
return todos;
});
readonly remaining = computed(() => this.todos().filter((t) => !t.done).length);
add(text: string) {
const todo = { id: this.nextId++, text, done: false };
this.state.update((s) => ({ ...s, todos: [...s.todos, todo] }));
}
toggle(id: number) {
this.state.update((s) => ({
...s,
todos: s.todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
}));
}
remove(id: number) {
this.state.update((s) => ({ ...s, todos: s.todos.filter((t) => t.id !== id) }));
}
setFilter(filter: Filter) {
this.state.update((s) => ({ ...s, filter }));
}
}
// src/app/todo-store.spec.ts
import { TestBed } from '@angular/core/testing';
import { TodoStore } from './todo-store';
describe('TodoStore', () => {
let store: TodoStore;
beforeEach(() => {
store = TestBed.inject(TodoStore);
});
it('starts with one todo left to do', () => {
expect(store.todos().length).toBe(2);
expect(store.remaining()).toBe(1);
});
it('adds a todo that is not done yet', () => {
store.add('Walk the dog');
const texts = store.todos().map((t) => t.text);
expect(texts).toEqual(['Buy milk', 'Call Ana', 'Walk the dog']);
expect(store.remaining()).toBe(2);
});
it('shows only done todos with the done filter', () => {
store.setFilter('done');
expect(store.visible().map((t) => t.text)).toEqual(['Call Ana']);
store.toggle(1);
expect(store.visible().map((t) => t.text)).toEqual(['Buy milk', 'Call Ana']);
});
});
ng test runs both spec files now:
Test Files 2 passed (2)
Tests 5 passed (5)
Some things to notice:
beforeEachruns before every test in thedescribe. Each test gets its own fresh store instore.let store: TodoStoredeclares the variable with its type, andbeforeEachfills it in.toEqualcompares the contents of two lists.toBewould ask whether they’re the same list, and a new array never is.- There’s no
awaitand nowhenStable()anywhere. Acomputedworks out its value when you read it (Part 3). Right afterstore.add(...),store.remaining()is already 2. Waiting is only needed for what Angular does later: rendering, effects and loading. - The test uses only the public API: actions and read-only signals. It can’t call
state.set(...), becausestateis private, and that’s good. A test that only uses the public API keeps passing when you change how the store works inside.
Testing a service that calls a server
Part 18 put requests in a BookApi service. A test for it shouldn’t call a real server. A server can be down, slow, or have different data tomorrow, and the test would fail for reasons that have nothing to do with your code. We’d also have to check what was sent, which a real server doesn’t tell you.
Angular has a stand-in for the server, the test backend. HttpClient doesn’t send requests itself. At the end of the interceptor chain it hands each request to a backend, which normally sends it with the browser’s fetch. provideHttpClientTesting() swaps that backend for one that sends nothing. It keeps each request in a list and waits. Your test then picks a request from the list, checks it, and answers it.
Everything up to the backend is the real code. Only the last step is swapped, and the test plays the server.
Your service, HttpClient and your interceptors all run for real. Only the backend is different. So the test checks the code you wrote, all the way to the point where a request would leave the app.
Here’s BookApi with the three methods from Part 18, and its test:
// src/app/book-api.ts
import { HttpClient } from '@angular/common/http';
import { Service, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface Book {
id: number;
title: string;
author: string;
}
@Service()
export class BookApi {
private readonly http = inject(HttpClient);
list(): Observable<Book[]> {
return this.http.get<Book[]>('/books.json');
}
byAuthor(author: string, limit: number): Observable<Book[]> {
return this.http.get<Book[]>('/books.json', { params: { author, limit } });
}
add(title: string, author: string): Observable<Book> {
return this.http.post<Book>('/api/books', { title, author });
}
}
// src/app/book-api.spec.ts
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { Book, BookApi } from './book-api';
describe('BookApi', () => {
let api: BookApi;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
api = TestBed.inject(BookApi);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('loads the list of books', () => {
let books: Book[] = [];
api.list().subscribe((result) => (books = result));
const req = httpTesting.expectOne('/books.json');
expect(req.request.method).toBe('GET');
req.flush([{ id: 1, title: 'Matilda', author: 'Roald Dahl' }]);
expect(books.length).toBe(1);
expect(books[0].title).toBe('Matilda');
});
});
Test Files 3 passed (3)
Tests 6 passed (6)
Here’s the test, piece by piece:
providers: [provideHttpClient(), provideHttpClientTesting()]. The second swaps the backend.HttpClientworks without the first one (Part 18), but you needprovideHttpClient()for interceptors, and Angular’s docs write both. If you write both, the order matters. We tried them the other way round, andprovideHttpClient()put the real backend back: the request went out tofetch, failed with status 0, and the test found no request in its list.TestBed.inject(HttpTestingController)gets the test’s handle on the test backend. Its usual name in tests ishttpTesting.api.list().subscribe(...)calls the service the way a component would. As Part 18 showed, nothing is sent until someone subscribes. The callback stores the result in a local variable.httpTesting.expectOne('/books.json')finds the one request for that URL and returns aTestRequest. If there’s no such request, or more than one, the test fails right there.req.requestis the realHttpRequestyour code sent. Check anything on it:method,url,headers,body,params.req.flush(body)answers it. The body goes back through the interceptors and into yoursubscribecallback, right away. That’s why the very next line can checkbooks. Nothing waits for a timer.httpTesting.verify()inafterEachfails the test if any request is still waiting for an answer. That catches a service that sends a request you didn’t expect, such as a second copy of the same one.
If your app has interceptors, give the test the same ones: provideHttpClient(withInterceptors([...])). They run in the test, before the test backend. We checked: an interceptor that adds an X-Client header shows up in req.request.headers.
Checking what was sent
Most bugs in HTTP code are in what you send: a wrong param, a missing field in the body. Here are tests for byAuthor and add. Add them inside the describe, below the first test. The whole file is in the worked example below.
it('sends the author and limit as query params', () => {
api.byAuthor('Roald Dahl', 2).subscribe();
const req = httpTesting.expectOne('/books.json?author=Roald%20Dahl&limit=2');
expect(req.request.params.get('author')).toBe('Roald Dahl');
req.flush([]);
});
it('posts the new book and returns the saved one', () => {
let saved: Book | undefined;
api.add('Holes', 'Louis Sachar').subscribe((book) => (saved = book));
const req = httpTesting.expectOne({ method: 'POST', url: '/api/books' });
expect(req.request.body).toEqual({ title: 'Holes', author: 'Louis Sachar' });
req.flush(
{ id: 4, title: 'Holes', author: 'Louis Sachar' },
{ status: 201, statusText: 'Created' },
);
expect(saved?.id).toBe(4);
});
expectOne with a string compares it to the whole URL, query params included. expectOne('/books.json') doesn’t match /books.json?author=.... expectOne also takes { method, url } to match both, or a function that gets each request and returns true for the right one. flush‘s second argument sets the response’s status, statusText and headers.
Book | undefined is a union type: saved is a book, or nothing yet. saved?.id reads id only if saved isn’t undefined.
Answering with an error
A test should also check what your code does when the server says no. flush with an error status delivers an HttpErrorResponse, exactly as a real 404 would:
it('reports a 404', () => {
let status = 0;
api.list().subscribe({ error: (err: HttpErrorResponse) => (status = err.status) });
const req = httpTesting.expectOne('/books.json');
req.flush('Not found', { status: 404, statusText: 'Not Found' });
expect(status).toBe(404);
});
To fake “the server couldn’t be reached”, call req.error(new ProgressEvent('error')) instead of flush. The HttpErrorResponse then has status 0, as Part 18 described for a real network failure.
Worked example: reading a failed HTTP test
Here’s the whole spec file with those tests, and two mistakes. The last test was meant to check that list() sends its request once:
// src/app/book-api.spec.ts
import { HttpErrorResponse, provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { Book, BookApi } from './book-api';
describe('BookApi', () => {
let api: BookApi;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
api = TestBed.inject(BookApi);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('loads the list of books', () => {
let books: Book[] = [];
api.list().subscribe((result) => (books = result));
const req = httpTesting.expectOne('/books.json');
expect(req.request.method).toBe('GET');
req.flush([{ id: 1, title: 'Matilda', author: 'Roald Dahl' }]);
expect(books.length).toBe(1);
expect(books[0].title).toBe('Matilda');
});
it('sends the author and limit as query params', () => {
api.byAuthor('Roald Dahl', 2);
const req = httpTesting.expectOne('/books.json?author=Roald%20Dahl&limit=2');
expect(req.request.params.get('author')).toBe('Roald Dahl');
req.flush([]);
});
it('posts the new book and returns the saved one', () => {
let saved: Book | undefined;
api.add('Holes', 'Louis Sachar').subscribe((book) => (saved = book));
const req = httpTesting.expectOne({ method: 'POST', url: '/api/books' });
expect(req.request.body).toEqual({ title: 'Holes', author: 'Louis Sachar' });
req.flush(
{ id: 4, title: 'Holes', author: 'Louis Sachar' },
{ status: 201, statusText: 'Created' },
);
expect(saved?.id).toBe(4);
});
it('reports a 404', () => {
let status = 0;
api.list().subscribe({ error: (err: HttpErrorResponse) => (status = err.status) });
const req = httpTesting.expectOne('/books.json');
req.flush('Not found', { status: 404, statusText: 'Not Found' });
expect(status).toBe(404);
});
it('sends one request for the list', () => {
api.list().subscribe();
api.list().subscribe();
httpTesting.expectOne('/books.json').flush([]);
});
});
ng test reports two failures. Here are the parts that matter, with the count from the end of the output. Your project’s name, practice, appears where these show lab.
FAIL |lab| src/app/book-api.spec.ts > BookApi > sends the author and limit as query params
Error: Expected one matching request for criteria "Match URL: /books.json?author=Roald%20Dahl&limit=2", found none.
...
FAIL |lab| src/app/book-api.spec.ts > BookApi > sends one request for the list
Error: Expected one matching request for criteria "Match URL: /books.json", found 2 requests.
...
Tests 2 failed | 8 passed (10)
Read each one in two parts:
FAILand the path name the file, thedescribeand theit, joined by>. That’s why clear test names pay off.- The
Error:line says whatHttpTestingControllerexpected and what it found. Below it (left out here), Vitest prints where the error came from, as lines starting with❯, then the line of your spec that failed, with a^under it. The first❯line points inside Angular; look for the one that names your.spec.tsfile.
The other 8 tests still ran and passed.
The first error says the request was never sent. api.byAuthor('Roald Dahl', 2) built an Observable, and nobody subscribed, so HttpClient did nothing. It’s the same mistake as Part 18’s “Try this first”, caught by a test. Add .subscribe().
The second says there were two requests for /books.json. Each subscribe() sends its own request, as Part 18 showed. Here the test was wrong: the code really does send two. If two subscribers were a bug in a real service, this is how you’d find it. Here we just delete the second subscribe().
With both fixed:
// src/app/book-api.spec.ts
import { HttpErrorResponse, provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { Book, BookApi } from './book-api';
describe('BookApi', () => {
let api: BookApi;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
api = TestBed.inject(BookApi);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('loads the list of books', () => {
let books: Book[] = [];
api.list().subscribe((result) => (books = result));
const req = httpTesting.expectOne('/books.json');
expect(req.request.method).toBe('GET');
req.flush([{ id: 1, title: 'Matilda', author: 'Roald Dahl' }]);
expect(books.length).toBe(1);
expect(books[0].title).toBe('Matilda');
});
it('sends the author and limit as query params', () => {
api.byAuthor('Roald Dahl', 2).subscribe();
const req = httpTesting.expectOne('/books.json?author=Roald%20Dahl&limit=2');
expect(req.request.params.get('author')).toBe('Roald Dahl');
req.flush([]);
});
it('posts the new book and returns the saved one', () => {
let saved: Book | undefined;
api.add('Holes', 'Louis Sachar').subscribe((book) => (saved = book));
const req = httpTesting.expectOne({ method: 'POST', url: '/api/books' });
expect(req.request.body).toEqual({ title: 'Holes', author: 'Louis Sachar' });
req.flush(
{ id: 4, title: 'Holes', author: 'Louis Sachar' },
{ status: 201, statusText: 'Created' },
);
expect(saved?.id).toBe(4);
});
it('reports a 404', () => {
let status = 0;
api.list().subscribe({ error: (err: HttpErrorResponse) => (status = err.status) });
const req = httpTesting.expectOne('/books.json');
req.flush('Not found', { status: 404, statusText: 'Not Found' });
expect(status).toBe(404);
});
it('sends one request for the list', () => {
api.list().subscribe();
httpTesting.expectOne('/books.json').flush([]);
});
});
Test Files 3 passed (3)
Tests 10 passed (10)
One more message to know. If a test sends a request and never answers it, verify() in afterEach fails with Expected no open requests, found 1: GET /books.json. Either the test forgot to flush, or the code sent something the test didn’t expect.
Testing a component that loads with httpResource
Part 19‘s UserCard loads a user by id with httpResource. httpResource goes through HttpClient, so the same test backend catches its requests. There’s one new problem: when the request is sent.
HttpClient.get sends when you subscribe. A resource sends later, when Angular next runs its scheduled work, after you set the input. In a test, that work runs on its own a moment later, but you need the request in the list now, so you can answer it. And fixture.whenStable() from Part 24 doesn’t help here. It waits until Angular has nothing pending, and a resource that’s loading counts as pending. We tried it: the test waited for an answer that only the test itself could give, and Vitest stopped it with Test timed out in 5000ms.
The fix is TestBed.tick(). It runs Angular’s pending work once, right now: effects, rendering, and the start of a resource’s load. Then the request is in the list, and you can answer it:
// src/app/user-card.ts
import { Component, input } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
email: string;
}
@Component({
selector: 'app-user-card',
template: `
@if (user.hasValue()) {
<h2>{{ user.value().name }}</h2>
<p>{{ user.value().email }}</p>
} @else if (user.error()) {
<p>Couldn't load user {{ userId() }} ({{ user.statusCode() }}).</p>
<button (click)="user.reload()">Try again</button>
} @else {
<p>Loading user {{ userId() }}...</p>
}
`,
})
export class UserCard {
readonly userId = input.required<number>();
protected readonly user = httpResource<User>(() => `/user-${this.userId()}.json`);
}
// src/app/user-card.spec.ts
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { UserCard } from './user-card';
describe('UserCard', () => {
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('shows the user once the request is answered', async () => {
const fixture = TestBed.createComponent(UserCard);
const el = fixture.nativeElement as HTMLElement;
fixture.componentRef.setInput('userId', 1);
TestBed.tick();
expect(el.textContent).toContain('Loading user 1...');
const user = { id: 1, name: 'Ana Silva', email: 'ana@example.com' };
httpTesting.expectOne('/user-1.json').flush(user);
await fixture.whenStable();
expect(el.querySelector('h2')?.textContent).toBe('Ana Silva');
});
it('shows the status code when the user is missing', async () => {
const fixture = TestBed.createComponent(UserCard);
const el = fixture.nativeElement as HTMLElement;
fixture.componentRef.setInput('userId', 3);
TestBed.tick();
httpTesting.expectOne('/user-3.json').flush('', { status: 404, statusText: 'Not Found' });
await fixture.whenStable();
expect(el.textContent).toContain("Couldn't load user 3 (404).");
});
});
Test Files 4 passed (4)
Tests 12 passed (12)
The order in each test is the order a real load goes through:
setInput('userId', 1)sets the input, as in Part 24. Nothing is sent yet.TestBed.tick()runs Angular’s work. The resource readsuserId(), builds the URL and sends the request. The template renders in its loading state, so the page saysLoading user 1....expectOne(...).flush(user)answers the request.await fixture.whenStable()now has something to wait for that will finish. The resource stores the value, and the template renders the user.
We ran these tests over and over, and they passed every time. They wait for nothing real: no fixed delay, no network. Every step happens because the test made it happen.
Testing a guard
Part 17‘s authGuard lets logged-in readers into /admin and sends everyone else to /login. A guard is a plain function, so the first idea is to just call it. Here are the store and the guard again, and a first try:
// src/app/auth-store.ts
import { Service, computed, signal } from '@angular/core';
@Service()
export class AuthStore {
private readonly userState = signal<string | null>(null);
readonly user = this.userState.asReadonly();
readonly loggedIn = computed(() => this.user() !== null);
logIn(name: string) {
this.userState.set(name);
}
logOut() {
this.userState.set(null);
}
}
// src/app/auth-guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthStore } from './auth-store';
export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthStore);
const router = inject(Router);
if (auth.loggedIn()) {
return true;
}
return router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};
// src/app/auth-guard.spec.ts
import { TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { authGuard } from './auth-guard';
import { AuthStore } from './auth-store';
describe('authGuard', () => {
const route = {} as ActivatedRouteSnapshot;
const state = { url: '/admin' } as RouterStateSnapshot;
it('lets a logged-in reader through', () => {
TestBed.inject(AuthStore).logIn('Ana');
expect(authGuard(route, state)).toBe(true);
});
});
A guard gets two arguments. This one never reads route, and reads only url from state. {} as ActivatedRouteSnapshot is a type assertion: it tells TypeScript to treat an empty object as that type. That’s fine in a test, as long as the guard really doesn’t read the parts you left out.
The test fails:
FAIL |lab| src/app/auth-guard.spec.ts > authGuard > lets a logged-in reader through
Error: NG0203: The `_AuthStore` token injection failed. `inject()` function must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://v22.angular.dev/errors/NG0203
...
Tests 1 failed | 12 passed (13)
NG0203 is the error from Part 13 for inject() outside an injection context. When the router runs a guard, it sets one up, so inject() knows which injector to ask. A plain call from a test has none. (As in Part 13, the build names Angular classes with a leading underscore; read _AuthStore as AuthStore.) The message even names the fix: runInInjectionContext.
TestBed.runInInjectionContext(fn) runs fn inside the test’s injector and returns what fn returns:
// src/app/auth-guard.spec.ts
import { TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { authGuard } from './auth-guard';
import { AuthStore } from './auth-store';
describe('authGuard', () => {
const route = {} as ActivatedRouteSnapshot;
const state = { url: '/admin' } as RouterStateSnapshot;
it('lets a logged-in reader through', () => {
TestBed.inject(AuthStore).logIn('Ana');
const result = TestBed.runInInjectionContext(() => authGuard(route, state));
expect(result).toBe(true);
});
it('sends everyone else to the login page', () => {
const result = TestBed.runInInjectionContext(() => authGuard(route, state));
expect(result).toBeInstanceOf(UrlTree);
const url = TestBed.inject(Router).serializeUrl(result as UrlTree);
expect(url).toBe('/login?returnUrl=%2Fadmin');
});
});
Test Files 5 passed (5)
Tests 14 passed (14)
The first test logs Ana in through the store’s own action, then asks the guard. The second leaves nobody logged in. The guard returns a UrlTree, and serializeUrl turns it back into the URL string, which is easy to compare. The Router here is the one Angular makes for any app; the test didn’t need provideRouter just to build a URL.
Testing routes with RouterTestingHarness
A guard test checks the function. It doesn’t check that the guard is on the right route, or that a page gets its parameter. For that, the test needs a real router doing real navigations. RouterTestingHarness from @angular/router/testing gives you one: a small test app with a <router-outlet>, driven from your test.
Here are the pages and routes from Parts 16 and 17 in one routes file:
// src/app/pages.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
template: `<h1>Home</h1>`,
})
export class Home {}
@Component({
selector: 'app-admin',
template: `<h1>Admin</h1>`,
})
export class Admin {}
// src/app/user-page.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-user-page',
template: `<p>User {{ id() }}</p>`,
})
export class UserPage {
readonly id = input.required<string>();
}
// src/app/login.ts
import { Component, inject, input } from '@angular/core';
import { Router } from '@angular/router';
import { AuthStore } from './auth-store';
@Component({
selector: 'app-login',
template: `
<h1>Log in</h1>
<button (click)="logIn()">Log in as Ana</button>
`,
})
export class Login {
readonly returnUrl = input<string>();
private readonly auth = inject(AuthStore);
private readonly router = inject(Router);
protected logIn() {
this.auth.logIn('Ana');
this.router.navigateByUrl(this.returnUrl() ?? '/');
}
}
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { authGuard } from './auth-guard';
import { Login } from './login';
import { Admin, Home } from './pages';
import { UserPage } from './user-page';
export const routes: Routes = [
{ path: '', component: Home },
{ path: 'login', component: Login },
{ path: 'admin', component: Admin, canActivate: [authGuard] },
{ path: 'users/:id', component: UserPage },
];
// src/app/app.routes.spec.ts
import { TestBed } from '@angular/core/testing';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { routes } from './app.routes';
import { UserPage } from './user-page';
describe('routes', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideRouter(routes, withComponentInputBinding())],
});
});
it('gives UserPage the id from the URL', async () => {
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl('/users/42', UserPage);
expect(page.id()).toBe('42');
expect(harness.routeNativeElement?.textContent).toBe('User 42');
});
it('keeps the same page when only the id changes', async () => {
const harness = await RouterTestingHarness.create();
const first = await harness.navigateByUrl('/users/1', UserPage);
const second = await harness.navigateByUrl('/users/2', UserPage);
expect(second).toBe(first);
expect(harness.routeNativeElement?.textContent).toBe('User 2');
});
});
Test Files 6 passed (6)
Tests 16 passed (16)
How it fits together:
- The test sets up the router itself, with
provideRouter(routes, withComponentInputBinding()). It imports the realroutes, so it tests your real route list. It does not readapp.config.ts. If your app turns onwithComponentInputBinding()there, turn it on here too, or route params won’t reach inputs. RouterTestingHarness.create()builds the test app and returns a Promise of the harness, so youawaitit. You can pass a first URL:create('/users/42').harness.navigateByUrl(url, UserPage)navigates and waits until the page has rendered. With a component class as the second argument, it returns that component’s instance, and it fails the test if a different component ended up in the outlet.- With the instance, you can read its inputs as signals:
page.id()is'42'. That checks the route param really reached the input. harness.routeNativeElementis the routed component’s own element, here the<app-user-page>. ItstextContentis what the page shows.
The second test checks a promise from Part 16: when only the param changes, the router keeps the same component and updates its input. toBe on two component instances asks whether they’re the same object, and they are.
Worked example: a login flow through the router
Now the guard, on its route. A visitor goes to /admin. A first try at the test:
// src/app/auth-flow.spec.ts
import { TestBed } from '@angular/core/testing';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { routes } from './app.routes';
import { Admin } from './pages';
describe('admin page', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideRouter(routes, withComponentInputBinding())],
});
});
it('shows the admin page', async () => {
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/admin', Admin);
});
});
It fails:
FAIL |lab| src/app/auth-flow.spec.ts > admin page > shows the admin page
Error: Unexpected routed component type. Expected _Admin but got _Login
...
Tests 1 failed | 16 passed (17)
The test asked for Admin in the outlet and got Login. The navigation itself worked. The guard did its job: nobody was logged in, so it redirected to /login. The test is the thing that’s wrong. Each test has a fresh AuthStore, so nobody is logged in unless the test logs someone in.
That’s a real behaviour worth testing. Let’s test the whole flow: get redirected, click the button, end up on the admin page.
// src/app/auth-flow.spec.ts
import { TestBed } from '@angular/core/testing';
import { Router, provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { routes } from './app.routes';
import { AuthStore } from './auth-store';
import { Login } from './login';
import { Admin } from './pages';
describe('admin page', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideRouter(routes, withComponentInputBinding())],
});
});
it('sends a visitor to log in, then back to admin', async () => {
const harness = await RouterTestingHarness.create();
const router = TestBed.inject(Router);
const login = await harness.navigateByUrl('/admin', Login);
expect(router.url).toBe('/login?returnUrl=%2Fadmin');
expect(login.returnUrl()).toBe('/admin');
harness.routeNativeElement?.querySelector('button')?.click();
await harness.fixture.whenStable();
expect(router.url).toBe('/admin');
expect(harness.routeNativeElement?.textContent).toBe('Admin');
});
it('lets a logged-in reader straight in', async () => {
TestBed.inject(AuthStore).logIn('Ana');
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/admin', Admin);
expect(TestBed.inject(Router).url).toBe('/admin');
});
});
Test Files 7 passed (7)
Tests 18 passed (18)
Step by step:
navigateByUrl('/admin', Login)now says what we expect: the guard redirects, andLoginends up in the outlet.router.urlis the URL the router is on, the same text you’d see in the address bar after the host name.login.returnUrl()checks that the redirect’s query param reached the login page’s input.- Clicking the button calls
logIn(), which starts a navigation withnavigateByUrl. A navigation takes more than one step, so weawait harness.fixture.whenStable(). The harness’sfixtureis a normalComponentFixture, like the ones in Part 24, wrapped around the test app. - The second test logs in before navigating, so the guard says yes.
This one test covers the store, the guard, the route list, the query param and the login page together. Keep both kinds: small tests that pin down one function, and a few flow tests that show the pieces really connect.
In older code
Older tests set things up with NgModules: imports: [HttpClientTestingModule] instead of provideHttpClientTesting(), and imports: [RouterTestingModule.withRoutes(routes)] instead of provideRouter(routes). Both still exist in Angular 22.3, and both are marked deprecated in its type definitions. Older guards were classes with a canActivate method, tested by creating the class. And in projects with zone.js, you’ll see tests wrapped in fakeAsync(() => { ... }), calling tick(500) to move a fake clock forward. That tick is a different function from TestBed.tick(), and a new zoneless Angular 22 project doesn’t use it.
Best practices
- Test stores through their public API. Call actions, read signals, with no
await. The tests survive changes inside the store, which replaces tests that poke at private state. - Use
HttpTestingControllerfor every HTTP test, and callverify()inafterEach. You check what was sent and control every answer, including errors. It replaces tests against a real server, which are slow and fail for reasons outside your code. - Test error answers, not just success. A
flushwith a 404 or 500 status, orerror(new ProgressEvent('error')), checks the branch users see on bad days. It’s the branch that’s never run by hand. - For a resource,
TestBed.tick()beforeexpectOne,whenStable()afterflush. The first starts the load; the second waits for the render. It replaces guessing withsetTimeout. - Test a guard both alone and on its route.
runInInjectionContextpins down each answer;RouterTestingHarnesschecks it’s wired to the right route. It replaces testing guards only by clicking through the app.
Tips and traps
provideHttpClientTesting()beforeprovideHttpClient(). The real backend wins. Requests go tofetch, fail with status 0, andexpectOnesaysfound none. PutprovideHttpClient()first.- Forgetting to
subscribe.expectOnefails withfound none, because anHttpClientObservable sends nothing until someone subscribes. Add.subscribe()in the test, or find the missing one in your code. expectOne('/books.json')for a request with params. It fails withfound noneand lists the request it did receive,GET /books.json?author=.... Match the whole URL, or use a function:expectOne((req) => req.url === '/books.json').await fixture.whenStable()before answering a resource’s request. The test hangs untilTest timed out in 5000ms, because the loading resource keeps Angular busy. CallTestBed.tick(),flush, thenwhenStable().- Calling a guard directly.
NG0203for its firstinject(). Wrap the call inTestBed.runInInjectionContext. - Route params that don’t reach inputs in a test. The test’s
provideRouterdoesn’t readapp.config.ts. Pass the same features, such aswithComponentInputBinding().
A test replaces the slow, outside parts with ones it controls, and runs everything else for real.
Exercises
Exercise 1. This test is meant to check that a page can load the books twice. It fails with found 2 requests, because expectOne wants exactly one. HttpTestingController also has match(url), which returns every waiting request for that URL as a list. Fix the test with it, so it checks there were two requests and answers both.
// src/app/book-api-twice.spec.ts
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { BookApi } from './book-api';
describe('BookApi, loading twice', () => {
it('sends a request each time', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const api = TestBed.inject(BookApi);
const httpTesting = TestBed.inject(HttpTestingController);
api.list().subscribe();
api.list().subscribe();
httpTesting.expectOne('/books.json').flush([]);
httpTesting.verify();
});
});
Error: Expected one matching request for criteria "Match URL: /books.json", found 2 requests.
...
Tests 1 failed | 18 passed (19)
Exercise 2. Write a test for UserCard‘s Try again button. The first request for user 3 gets a 404. The test clicks Try again, answers the second request with a user named Chen Li, and checks the card shows Chen Li.
Exercise 3. Write a RouterTestingHarness test that /users/ana shows User ana, starting the harness at that URL with RouterTestingHarness.create('/users/ana') instead of calling navigateByUrl.
Answers
1. match(url) returns every waiting request that matches, as a list, without failing. Check the length, then flush each one:
// src/app/book-api-twice.spec.ts
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { BookApi } from './book-api';
describe('BookApi, loading twice', () => {
it('sends a request each time', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const api = TestBed.inject(BookApi);
const httpTesting = TestBed.inject(HttpTestingController);
api.list().subscribe();
api.list().subscribe();
const requests = httpTesting.match('/books.json');
expect(requests.length).toBe(2);
requests.forEach((req) => req.flush([]));
httpTesting.verify();
});
});
Test Files 8 passed (8)
Tests 19 passed (19)
verify() at the end passes, because both requests were answered. match took them off the waiting list.
2. The click works like a new input value: it asks the resource to load again, and TestBed.tick() sends the request.
// src/app/user-card-retry.spec.ts
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { UserCard } from './user-card';
describe('UserCard, Try again', () => {
it('loads the user again after an error', async () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const httpTesting = TestBed.inject(HttpTestingController);
const fixture = TestBed.createComponent(UserCard);
const el = fixture.nativeElement as HTMLElement;
fixture.componentRef.setInput('userId', 3);
TestBed.tick();
httpTesting.expectOne('/user-3.json').flush('', { status: 404, statusText: 'Not Found' });
await fixture.whenStable();
el.querySelector('button')?.click();
TestBed.tick();
const user = { id: 3, name: 'Chen Li', email: 'chen@example.com' };
httpTesting.expectOne('/user-3.json').flush(user);
await fixture.whenStable();
expect(el.querySelector('h2')?.textContent).toBe('Chen Li');
httpTesting.verify();
});
});
Test Files 9 passed (9)
Tests 20 passed (20)
3. create with a URL navigates there first. routeNativeElement then holds the page:
// src/app/user-route.spec.ts
import { TestBed } from '@angular/core/testing';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { routes } from './app.routes';
describe('users route', () => {
it('shows the user named in the URL', async () => {
TestBed.configureTestingModule({
providers: [provideRouter(routes, withComponentInputBinding())],
});
const harness = await RouterTestingHarness.create('/users/ana');
expect(harness.routeNativeElement?.textContent).toBe('User ana');
});
});
Test Files 10 passed (10)
Tests 21 passed (21)
What’s next
Our tests used TestBed.tick() and whenStable() to make Angular render when we said so. In Part 26, we’ll look at what Angular does in that render: OnPush by default, zoneless scheduling, and how a signal marks just the views that read it.