Sub topic 13
Testing failures and retries with HttpTestingController
This chapter assumes you can write a basic Angular test with TestBed, and that you have read the earlier chapters on catchError, the retry operator, and the retry interceptor. Here you will test those pieces without a server. You will fake each response, including failures, and control time so that backoff delays run instantly.
How HttpTestingController works
provideHttpClientTesting() replaces the real HTTP backend with a fake one. Requests go nowhere. Each one is recorded, and your test decides how it ends. HttpTestingController is the handle you use to find those recorded requests.
| Member | Purpose |
|---|---|
| `expectOne(url)` | Finds exactly one pending request that matches. It fails if there are zero or several. |
| `expectNone(url)` | Asserts that no pending request matches. |
| `match(predicate)` | Returns every pending request that matches, so you can inspect several at once. |
| `req.flush(body, opts)` | Completes the request with a response. A `status` of 400 or higher produces an `HttpErrorResponse`. |
| `req.error(event)` | Fails the request with a network-level error. The resulting status is `0`. |
| `verify()` | Fails the test if any request is still unanswered. |
Always call verify() in afterEach. It catches a request you forgot to answer and a retry you did not expect.
Testing a mapped error
The service from the catchError chapter turns an HttpErrorResponse into an Error. This test fakes a 404 and checks the resulting message.
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');
});
});Provider order matters. provideHttpClient() comes first, and provideHttpClientTesting() second overrides its backend.
The expect runs after flush, not inside the subscribe callback. flush runs the subscriber synchronously. If you put the assertion inside the callback and the response never arrives, the assertion never executes and the test passes anyway.
Simulating a network failure
A 404 is a server response. A dropped connection is different, and flush cannot produce it. Use error() with a ProgressEvent. Add this test inside the same describe block.
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.');
});The fake backend wraps the event in an HttpErrorResponse with status 0, which is what a real browser reports. These two tests cover both branches of the service's if.
Controlling time for retries
A retry with backoff waits before it resubscribes. Real waiting would make a suite slow, since the delays total 3.5 seconds. Angular's fakeAsync zone replaces timers with a virtual clock, and tick(ms) advances it.
Each retry sends a new request through the controller. After a failure, no request is pending until the delay has elapsed. You therefore alternate between flush, tick, and expectOne.
Testing the retry interceptor
Register the interceptor in the test module, exactly as the application does. Then call HttpClient directly, because the interceptor is the unit under test.
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';
const UNAVAILABLE = { status: 503, statusText: 'Service Unavailable' };
describe('retryInterceptor', () => {
let http: HttpClient;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([retryInterceptor])),
provideHttpClientTesting(),
],
});
http = TestBed.inject(HttpClient);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => httpMock.verify());
it('waits 500 ms, then succeeds on the second attempt', fakeAsync(() => {
const results: unknown[] = [];
http.get('/api/data').subscribe((r) => results.push(r));
httpMock.expectOne('/api/data').flush('fail', UNAVAILABLE);
tick(499);
httpMock.expectNone('/api/data');
tick(1);
httpMock.expectOne('/api/data').flush({ ok: true });
expect(results).toEqual([{ ok: true }]);
}));
it('gives up after three retries with doubling delays', fakeAsync(() => {
const errors: HttpErrorResponse[] = [];
http.get('/api/data').subscribe({ error: (e: HttpErrorResponse) => errors.push(e) });
httpMock.expectOne('/api/data').flush('fail', UNAVAILABLE);
for (const delay of [500, 1000, 2000]) {
tick(delay);
httpMock.expectOne('/api/data').flush('fail', UNAVAILABLE);
}
expect(errors.length).toBe(1);
expect(errors[0]?.status).toBe(503);
}));
});The first test checks the boundary. At 499 ms nothing has been sent, and at 500 ms the retry appears. The second test counts four requests in total: the original plus three retries. The fourth failure is not retried, so the error reaches the subscriber. If someone changes count or the delay formula, one of these tests fails.
Testing what must not be retried
The policy matters as much as the retries. Add these two tests inside the retryInterceptor describe block.
it('does not retry a POST', fakeAsync(() => {
const errors: HttpErrorResponse[] = [];
http.post('/api/orders', {}).subscribe({ error: (e: HttpErrorResponse) => errors.push(e) });
httpMock.expectOne('/api/orders').flush('fail', UNAVAILABLE);
tick(5000);
httpMock.expectNone('/api/orders');
expect(errors.length).toBe(1);
}));
it('does not retry a 404', fakeAsync(() => {
const errors: HttpErrorResponse[] = [];
http.get('/api/missing').subscribe({ error: (e: HttpErrorResponse) => errors.push(e) });
httpMock.expectOne('/api/missing').flush('nope', { status: 404, statusText: 'Not Found' });
tick(5000);
httpMock.expectNone('/api/missing');
expect(errors[0]?.status).toBe(404);
}));Ticking past the longest possible delay makes expectNone meaningful. Without the tick, a retry that was only scheduled would not yet be visible, and the test would pass for the wrong reason.
Testing a timeout
If you added a timeout operator, the same technique applies. Subscribe, never flush, and tick past the limit. Then assert that the subscriber received the timeout error. The TestRequest returned by expectOne also has a cancelled property. It is true once the subscriber unsubscribes, which timeout does when it fires. That confirms the abandoned request was cancelled.
Common mistakes
- Missing
verify(). Without it, an unanswered request or an unexpected extra retry goes unnoticed. - Using
flushfor a network error. It produces a response with a status code. Useerror()to get status0. - Calling
expectOnebefore the delay. The retry has not been issued yet, so you get "Expected one matching request, found none." Calltickfirst. - Using real timers. Without
fakeAsync, a test with a 2-second delay either waits or finishes before the retry fires. Jasmine'sdonecallback andsetTimeoutworkarounds are slower and more fragile. - Asserting inside
subscribe. Collect values in an array and assert after the flush, as shown above.
Exercises
Exercise
A test subscribes to a GET request through the retry interceptor, flushes a 503, and then immediately calls httpMock.expectOne('/api/data') without tick. The test fails. Why, and how do you fix it?
Show answer
The retry waits for timer(500) before resubscribing, so no second request exists yet. Wrap the test in fakeAsync and call tick(500) before expectOne.
Exercise
You want to confirm that a failed connection (not an HTTP error status) reaches your catchError branch for status === 0. Which controller call do you use on the pending request, and what argument does it take?
Show answer
Call error(new ProgressEvent('error')) on the TestRequest returned by expectOne. flush always produces a response with a status code, so it cannot simulate a network failure.