Sub topic 10
Testing HTTP errors and network failures
This chapter assumes you can write a basic Angular service test with TestBed. It also assumes you have provideHttpClient() and provideHttpClientTesting() configured and can use expectOne and flush for a successful response. The examples work with Jasmine or Jest. They use only describe, it, expect, and matchers that both frameworks provide.
How HttpClient reports failure
HttpClient treats a failed request as an error notification on the Observable, not as a value. Two different situations produce that notification, and both arrive as an HttpErrorResponse:
- The server answered with a non-2xx status. The
statusis the real code, such as 404 or 500. The response body, if any, is in theerrorproperty. - No response arrived. This covers a dropped connection, a CORS rejection, or a request that never left the browser. The
statusis0, anderrorholds the underlying event.
Your service code usually branches on these cases, so each branch needs its own test. HttpTestingController lets you trigger either situation on demand.
Simulating an HTTP error with flush
flush is not limited to success. If you pass a status outside the 200 to 299 range in its options, the test request emits an HttpErrorResponse instead of a value. This example reuses the UserService from earlier in the tutorial, with the setup repeated so it runs on its own:
import { TestBed } from '@angular/core/testing';
import { HttpErrorResponse, provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
describe('UserService errors', () => {
let service: UserService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserService);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('surfaces a 404 as an HttpErrorResponse', () => {
let caught: HttpErrorResponse | undefined;
service.getUser(99).subscribe({
error: (e: HttpErrorResponse) => (caught = e),
});
httpTesting
.expectOne('/api/users/99')
.flush('Not found', { status: 404, statusText: 'Not Found' });
expect(caught).toBeDefined();
expect(caught?.status).toBe(404);
expect(caught?.statusText).toBe('Not Found');
expect(caught?.error).toBe('Not found');
});
});The first argument to flush becomes caught.error. If your API returns a JSON error body, pass an object, and the test can assert on the same shape your production code reads:
httpTesting
.expectOne('/api/users/99')
.flush({ code: 'USER_NOT_FOUND' }, { status: 404, statusText: 'Not Found' });Always set statusText when it matters to the code under test. Without it, the value is an empty string.
Simulating a network failure with error
A network failure has no status code and no body, so flush is the wrong tool. Use the error method on the test request and pass it an event:
it('surfaces a network failure with status 0', () => {
let caught: HttpErrorResponse | undefined;
service.getUser(1).subscribe({ error: (e: HttpErrorResponse) => (caught = e) });
httpTesting.expectOne('/api/users/1').error(new ProgressEvent('error'));
expect(caught).toBeDefined();
expect(caught?.status).toBe(0);
expect(caught?.error).toBeInstanceOf(ProgressEvent);
});The event you pass appears unchanged as caught.error. The request counts as handled, so verify() in afterEach is satisfied. error also accepts a second argument with status and statusText. Most tests leave it out, because the default status 0 is exactly the "no response" case.
| Situation | Test call | `status` | `error` property |
|---|---|---|---|
| Server rejects the request | `flush(body, { status: 400, statusText: '...' })` | 400 | The body you passed |
| Server fails | `flush(body, { status: 500, statusText: '...' })` | 500 | The body you passed |
| Connection lost or blocked | `error(new ProgressEvent('error'))` | 0 | The event you passed |
Testing code that handles errors
Testing that an error propagates is a weak test. The more valuable tests cover code that reacts to errors. Here is a service that treats a 404 as "no such user" and lets everything else through:
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, catchError, of, throwError } from 'rxjs';
import { User } from './user.service';
@Injectable({ providedIn: 'root' })
export class LookupService {
private readonly http = inject(HttpClient);
findUser(id: number): Observable<User | null> {
return this.http.get<User>(`/api/users/${id}`).pipe(
catchError((e: HttpErrorResponse) =>
e.status === 404 ? of(null) : throwError(() => e),
),
);
}
}This logic has three paths, and each gets a test. The setup is the same as before, with LookupService injected:
describe('LookupService', () => {
let service: LookupService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(LookupService);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => httpTesting.verify());
it('returns null when the user does not exist', () => {
let result: User | null | undefined;
service.findUser(7).subscribe((u) => (result = u));
httpTesting
.expectOne('/api/users/7')
.flush('', { status: 404, statusText: 'Not Found' });
expect(result).toBeNull();
});
it('rethrows server errors', () => {
let caught: HttpErrorResponse | undefined;
service.findUser(7).subscribe({ error: (e) => (caught = e) });
httpTesting
.expectOne('/api/users/7')
.flush('boom', { status: 500, statusText: 'Server Error' });
expect(caught?.status).toBe(500);
});
it('rethrows network failures', () => {
let caught: HttpErrorResponse | undefined;
service.findUser(7).subscribe({ error: (e) => (caught = e) });
httpTesting.expectOne('/api/users/7').error(new ProgressEvent('error'));
expect(caught?.status).toBe(0);
});
});In the first test, result starts as undefined and the assertion expects null. The two values are different, so the test fails if the subscriber never ran. That is the same guard as in the earlier warning, built into the choice of initial value.
Errors with async and await
If you prefer async tests, convert the Observable with firstValueFrom. A rejected promise carries the HttpErrorResponse. Attach the rejection handler before you flush, so the rejection is never unhandled:
import { firstValueFrom } from 'rxjs';
it('rejects with the HttpErrorResponse', async () => {
const outcome = firstValueFrom(service.getUser(5)).then(
() => 'resolved' as const,
(e: HttpErrorResponse) => e,
);
httpTesting
.expectOne('/api/users/5')
.flush('boom', { status: 500, statusText: 'Server Error' });
const result = await outcome;
expect(result).toBeInstanceOf(HttpErrorResponse);
expect((result as HttpErrorResponse).status).toBe(500);
});The request must be flushed before the await. The Observable does nothing until expectOne and flush run, so awaiting first would hang the test until it times out.
Common mistakes
- Using
flushwith status 0 for a network error. Useerror(new ProgressEvent('error')). It describes the situation accurately and matches what the browser produces. - Asserting inside callbacks only. Store the value and assert after the flush, so a missing notification fails the test.
- Testing only the happy status. If production code branches on
status, test one status on each side of every branch. A 404 test says nothing about how a 500 is handled. - Forgetting that errors are final. After an error notification the Observable is finished. Calling
flushagain on the sameTestRequestthrows. To model a second attempt, the service has to issue a new request, which is the subject of the retry chapter. - Matching a different request than intended.
expectOnethrows if zero or several requests match. That failure usually means the service sent a different URL or method than you expected, not that the error simulation is broken.
Exercise
A service method calls http.get('/api/orders') and uses catchError to return an empty array when the status is 0 but rethrow any other error. Which two tests do you write, and which TestRequest call does each use?
Show answer
Test 1 simulates the network failure with httpTesting.expectOne('/api/orders').error(new ProgressEvent('error')) and asserts that the subscriber receives []. Test 2 simulates a server failure with httpTesting.expectOne('/api/orders').flush('boom', { status: 500, statusText: 'Server Error' }) and asserts that the error callback received an HttpErrorResponse with status 500. In both tests, store the result in a variable and assert after the flush, so a missing notification fails the test.
Exercise
Why does expect(caught?.status).toBe(404) inside the error callback give weaker protection than storing caught and asserting after the flush?
Show answer
If the request unexpectedly succeeds, the error callback never runs, so the assertion inside it never executes and the test passes. Asserting after the flush, ideally with expect(caught).toBeDefined() first, makes the test fail when no error is emitted.