Sub topic 10
Testing HTTP errors and network failures
This chapter assumes you can read TypeScript and RxJS, know how HttpClient returns Observables, and have already configured provideHttpClient() and provideHttpClientTesting() in TestBed. It builds on the UserService and the HttpTestingController setup from the earlier chapters.
Why error paths need their own tests
Most bugs in HTTP code show up when the server fails, not when it succeeds. A service may swallow an error, rethrow it in the wrong shape, or retry when it should not. With HttpTestingController you can force any failure without a backend, so these cases are cheap to cover.
Angular reports two kinds of failure, and both arrive in the Observable's error callback as an HttpErrorResponse:
- HTTP errors. The server answered with a non-2xx status such as 404 or 500. The
statusproperty holds that code. - Network errors. No response arrived at all, for example because the connection dropped or the request was blocked. The
statusproperty is0.
Simulating an HTTP error with flush
flush accepts a body and an options object. When status is outside the 200 range, the Observable errors instead of emitting.
import { HttpErrorResponse } from '@angular/common/http';
it('surfaces a 404 as an HttpErrorResponse', () => {
let status: number | undefined;
service.getUser(99).subscribe({
error: (e: HttpErrorResponse) => (status = e.status),
});
httpTesting
.expectOne('/api/users/99')
.flush('Not found', { status: 404, statusText: 'Not Found' });
expect(status).toBe(404);
});The body ('Not found') ends up in e.error. The statusText option is optional, but setting it keeps the HttpErrorResponse realistic.
Notice the order. You subscribe first, because HttpClient is lazy and sends nothing until then. Only after that can expectOne find the request, and flush then triggers the error callback synchronously. That is why the assertion can sit on the next line without any await.
Simulating a network failure with error
A real network failure has no status and no body. The error method on the captured request models this. It takes a ProgressEvent, which is what the browser raises in that situation.
it('surfaces a network failure', () => {
let error: HttpErrorResponse | undefined;
service.getUser(1).subscribe({ error: (e) => (error = e) });
httpTesting.expectOne('/api/users/1').error(new ProgressEvent('error'));
expect(error?.status).toBe(0);
});This matters because code that branches on status often treats 0 as "offline" and shows a different message from a 500. Testing both branches confirms the branching works.
Testing retries against failures
The getUserWithRetry method uses retry(2), which resubscribes on error, up to two extra times. Each resubscription sends a new request, so the test must answer each one in turn.
it('retries a failed request and succeeds on the third attempt', () => {
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' });
});Each expectOne matches and removes one pending request. If the service retried only once, the third expectOne would fail with a "no match" error, which is the signal you want.
Common mistakes
- Forgetting to subscribe. No subscription means no request, and
expectOnefails with a message that no matching request was found. - Passing a 2xx status to
flushand expecting an error. Statuses from 200 to 299 produce a normal emission. - Expecting
statusof 0 fromflush. Useerror()for network failures.flushis for responses that actually came back. - Leaving a request unanswered. The
verify()call inafterEachfails the test in that case.
Exercise
Exercise
A service method calls http.get('/api/items') with retry(1). In a test, you subscribe, then call expectOne('/api/items').flush('x', { status: 503, statusText: 'Unavailable' }) once and finish the test. What happens, and why?
Show answer
The test fails. The first failure triggers one retry, which sends a second request to the same URL. Nothing answers that request, so httpTesting.verify() in afterEach reports an outstanding request. To fix it, call expectOne a second time and flush it, either with another error to check the final error is delivered, or with a body to check recovery.
Exercise
Which call do you use to make the Observable error with status 0, and which call makes it error with status 500?
Show answer
Use testRequest.error(new ProgressEvent('error')) for status 0, and testRequest.flush(body, { status: 500, statusText: 'Server Error' }) for status 500.