Sub topic 2
Setting Up HttpClient for Testing
This chapter assumes TypeScript basics, Angular dependency injection, RxJS Observables, HttpClient, and Angular CLI unit tests. The goal is to test what a service sends without contacting a real backend.
Configure a test HTTP backend
Use provideHttpClient() to register Angular's HTTP services. Add provideHttpClientTesting() after it to replace the real backend with a test backend. Requests then remain pending until the test matches and answers them.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { UserService } from './user.service';
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();
});
});HttpTestingController is the test API for finding pending requests. verify() fails the test if a request remains unanswered or an unexpected request was created.
Match and inspect requests
Call the service method first. Then use expectOne() to capture the pending request. An object matcher can check the method and the complete URL, including query parameters.
it('sends the requested page', () => {
service.listUsers(2).subscribe();
const request = httpTesting.expectOne({
method: 'GET',
url: '/api/users?page=2',
});
expect(request.request.method).toBe('GET');
expect(request.request.params.get('page')).toBe('2');
request.flush([]);
});You can also inspect headers and the body:
expect(request.request.headers.get('Authorization'))
.toBe('Bearer test-token');
expect(request.request.body).toEqual({ name: 'Ada' });Use an exact URL when possible. It prevents a test from accepting a request sent to the wrong endpoint.
Answer requests with `flush`
flush() supplies the response body and completes the pending request. The subscriber then receives the supplied value.
it('returns the server response', () => {
let result: unknown;
service.getUser(1).subscribe((user) => {
result = user;
});
httpTesting
.expectOne('/api/users/1')
.flush({ id: 1, name: 'Ada' });
expect(result).toEqual({ id: 1, name: 'Ada' });
});A test should flush every matched request. Otherwise verify() reports unfinished HTTP work.
Exercise
Which provider replaces the real HTTP backend, and which method supplies a response?
Show answer
provideHttpClientTesting() replaces the backend, and flush() supplies the response.