Sub topic 3
Testing HTTP Errors and Network Failures
Assume you know TypeScript, Angular dependency injection, RxJS Observables, and the standard TestBed setup with HttpTestingController.
Testing HTTP errors and network failures
Use flush with a status option to simulate an HTTP response such as 404 or 500. Use error to simulate a network-level failure. Network failures usually have status 0.
it('handles a 404 response', () => {
let status: number | undefined;
service.getUser(99).subscribe({
error: (error: HttpErrorResponse) => (status = error.status),
});
httpTesting
.expectOne('/api/users/99')
.flush('Not found', { status: 404, statusText: 'Not Found' });
expect(status).toBe(404);
});
it('handles a network failure', () => {
let status: number | undefined;
service.getUser(1).subscribe({
error: (error: HttpErrorResponse) => (status = error.status),
});
httpTesting
.expectOne('/api/users/1')
.error(new ProgressEvent('error'));
expect(status).toBe(0);
});Catching stray requests with `verify`
Call verify() in afterEach. It fails when a request remains unanswered, which catches forgotten flush calls and unexpected requests.
afterEach(() => {
httpTesting.verify();
});A successful test should account for every request it causes.
Testing retries
With retry(2), the original request plus two retries create three requests. Match and answer each one in order.
it('succeeds after two failed attempts', () => {
let result: User | undefined;
service.getUserWithRetry(1).subscribe((user) => (result = user));
httpTesting.expectOne('/api/users/1')
.flush('fail', { status: 500, statusText: 'Server Error' });
httpTesting.expectOne('/api/users/1')
.flush('fail', { status: 500, statusText: 'Server Error' });
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
expect(result).toEqual({ id: 1, name: 'Ada' });
});Testing functional interceptors
Register the interceptor with withInterceptors. Inspect the captured request after the interceptor has modified it.
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),http.get('/api/ping').subscribe();
const request = httpTesting.expectOne('/api/ping');
expect(request.request.headers.get('Authorization'))
.toBe('Bearer test-token');
request.flush({});Common pitfalls and maintainability
- Match the full URL, including query parameters, when the URL matters.
- Assert method, headers, parameters, and body when they are part of the service contract.
- Do not test private implementation details.
- Keep one behavior per test.
- Use descriptive request matchers instead of accepting any request.
- Always flush or fail every captured request.
Exercise
How many requests should a test answer for a service using retry(2)?
Show answer
Three: the initial request and two retries.