Sub topic 6
Setting up HttpClient for testing
This chapter assumes you know TypeScript, Angular services with dependency injection, RxJS Observables, the basics of HttpClient, and how to run unit tests with the Angular CLI. You will configure TestBed so that HttpClient requests never reach the network, then write a first test against UserService.
Why the real backend must go
A service that calls HttpClient sends real requests when it runs in a test. That makes the test slow and flaky, and it fails when no server is running. It also leaves you unable to control what the server answers.
Angular solves this with a replacement backend. It records each request instead of sending it. Your test then decides when and how that request is answered.
The two providers
Two functions set this up:
provideHttpClient()registersHttpClientitself, so your service can inject it.provideHttpClientTesting()replaces the real HTTP backend with a testing backend.
Order matters when you use both. Register provideHttpClient() first, then provideHttpClientTesting(). If you add interceptors with withInterceptors, pass them to provideHttpClient, as shown in a later chapter.
The subject under test
Here is the service this chapter tests.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { retry } from 'rxjs/operators';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserService {
private readonly http = inject(HttpClient);
getUser(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`);
}
getUserWithRetry(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`).pipe(retry(2));
}
listUsers(page: number): Observable<User[]> {
return this.http.get<User[]>('/api/users', { params: { page } });
}
}Configuring TestBed
Put the setup in beforeEach, so each test starts with a fresh configuration.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
describe('UserService', () => {
let service: UserService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserService);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('requests a user by id and returns the response body', () => {
let result: User | undefined;
service.getUser(1).subscribe((user) => (result = user));
const req = httpTesting.expectOne('/api/users/1');
expect(req.request.method).toBe('GET');
req.flush({ id: 1, name: 'Ada' });
expect(result).toEqual({ id: 1, name: 'Ada' });
});
});The setup does four things:
configureTestingModuleregisters the two providers.TestBed.inject(UserService)creates the service. Because it isprovidedIn: 'root', no extra provider is needed. It receives the testingHttpClient.TestBed.inject(HttpTestingController)gives you the handle to the fake backend.afterEachcallsverify(), which fails the test if any request was left unanswered or was never expected.
How a request flows in a test
The test controls the timing. Nothing is answered until you call flush.
Note that the request exists only after you subscribe. An Observable from HttpClient is cold, so calling service.getUser(1) without subscribe sends nothing, and expectOne then fails with "no match".
Common setup mistakes
| Symptom | Likely cause |
|---|---|
| `NullInjectorError: No provider for HttpClient` | `provideHttpClient()` is missing |
| `NullInjectorError: No provider for HttpTestingController` | `provideHttpClientTesting()` is missing |
| `Expected one matching request ... found none` | The Observable was never subscribed to, or the URL differs |
| `Expected no open requests, found 1` | A request was not flushed before `verify()` ran |
Exercise
Your test calls service.getUser(1) and then httpTesting.expectOne('/api/users/1'), but it fails with "Expected one matching request, found none". Both providers are configured. What is the most likely cause, and how do you fix it?
Show answer
The test never subscribed. An HttpClient Observable is cold and sends no request until something subscribes. Call .subscribe() on the result of service.getUser(1) before calling expectOne.