Sub topic 13
Testing failures and retries with HttpTestingController
This chapter assumes you can write an Angular service that uses HttpClient. It also assumes you know catchError and retry, and that you have read the chapter on the retry interceptor. Here you will test the error mapping and the retry behavior without a real server.
How HttpTestingController works
provideHttpClientTesting() replaces the real HTTP backend with a fake one. Requests never leave the test. They queue up inside HttpTestingController, and your test decides how each one ends.
These are the methods you will use most:
| Method | Purpose |
|---|---|
| `expectOne(url)` | Returns the one matching request and fails if there are zero or several. |
| `flush(body, opts)` | Completes the request with a response. A status outside 200-299 produces an `HttpErrorResponse`. |
| `error(event)` | Simulates a network failure. The resulting `HttpErrorResponse` has status 0. |
| `verify()` | Fails if any request is still outstanding. |
Testing the error mapping
The 404 test from the service looks like this:
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 httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => httpMock.verify());
it('maps a 404 response to an error message', () => {
let message = '';
service.getUser(1).subscribe({ error: (e: Error) => (message = e.message) });
httpMock
.expectOne('/api/users/1')
.flush('Not found', { status: 404, statusText: 'Not Found' });
expect(message).toBe('Server returned 404');
});
it('maps a network failure to a connection message', () => {
let message = '';
service.getUser(1).subscribe({ error: (e: Error) => (message = e.message) });
httpMock.expectOne('/api/users/1').error(new ProgressEvent('error'));
expect(message).toBe('Network error. Check your connection.');
});
});Call flush only after you subscribe. An Observable from HttpClient is cold, so no request exists until a subscriber appears. Without the subscription, expectOne fails.
Testing retries
Register the interceptor in the test module, the same way the app does. The retry delays use timers, so wrap each test in fakeAsync and move time forward with tick.
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { retryInterceptor } from './retry.interceptor';
describe('retryInterceptor', () => {
let http: HttpClient;
let httpMock: HttpTestingController;
const unavailable = { status: 503, statusText: 'Service Unavailable' };
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([retryInterceptor])),
provideHttpClientTesting(),
],
});
http = TestBed.inject(HttpClient);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => httpMock.verify());
it('retries a GET after a 503 and then succeeds', fakeAsync(() => {
let result: unknown;
http.get('/api/data').subscribe((r) => (result = r));
httpMock.expectOne('/api/data').flush('fail', unavailable);
tick(500);
httpMock.expectOne('/api/data').flush({ ok: true });
expect(result).toEqual({ ok: true });
}));
it('does not retry a 404', () => {
let status = 0;
http.get('/api/data').subscribe({ error: (e: HttpErrorResponse) => (status = e.status) });
httpMock.expectOne('/api/data').flush('Not found', { status: 404, statusText: 'Not Found' });
expect(status).toBe(404);
});
it('gives up after three retries', fakeAsync(() => {
let status = 0;
http.get('/api/data').subscribe({ error: (e: HttpErrorResponse) => (status = e.status) });
httpMock.expectOne('/api/data').flush('fail', unavailable);
tick(500);
httpMock.expectOne('/api/data').flush('fail', unavailable);
tick(1000);
httpMock.expectOne('/api/data').flush('fail', unavailable);
tick(2000);
httpMock.expectOne('/api/data').flush('fail', unavailable);
expect(status).toBe(503);
}));
});The tick values match the backoff of 500 ms, 1 s and 2 s. The final test sees four requests: the original and three retries. The afterEach call to verify() confirms that no request was left unanswered.
Common mistakes
- Forgetting
tick. The retry waits on a timer, soexpectOnefinds nothing and fails. - Calling
flushwith a 2xx status and expecting an error. Only non-2xx statuses, orerror(), produce anHttpErrorResponse. - Skipping
verify(). A request you never answered goes unnoticed, and the test can pass for the wrong reason.
Exercise
In the "gives up after three retries" test, why must the test call tick(2000) before the fourth expectOne, and what would happen if it called tick(1000) instead?
Show answer
The third retry waits 2 * (3 - 1) 500 = 2000 ms after the third failure. With only tick(1000) the timer has not fired, so the fourth request has not been sent and expectOne fails because it finds no matching request.