Sub topic 14
Testing HTTP Services
This chapter assumes you can write Jasmine or Jest specs with describe, it and expect, and that you have the TodoService from earlier chapters. A unit test for an HTTP service should never reach a real server. A real server makes tests slow and flaky, and the results depend on data you don't control. Angular solves this with a testing backend that captures each request so your test can inspect it and decide what response comes back.
How the testing backend works
You need two providers. provideHttpClient() registers the normal client. provideHttpClientTesting() must come after it, because it replaces the real backend with a mock. When the service makes a call, the request waits inside HttpTestingController until the test answers it with flush() or error().
A first test
// todo.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Todo, TodoService } from './todo.service';
describe('TodoService', () => {
let service: TodoService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()]
});
service = TestBed.inject(TodoService);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => httpTesting.verify());
it('requests the first page of todos', () => {
const mockTodos: Todo[] = [{ id: 1, title: 'Write tests', completed: false }];
let result: Todo[] | undefined;
service.getTodos(1).subscribe(todos => (result = todos));
const req = httpTesting.expectOne('/api/todos?page=1');
expect(req.request.method).toBe('GET');
req.flush(mockTodos);
expect(result).toEqual(mockTodos);
});
});Notice the order. You subscribe first, because an HttpClient Observable is cold and sends nothing until something subscribes. After that you match the request, and you flush last. expectOne fails the test if zero requests match, or if more than one does. verify() in afterEach fails the test if any request was left unanswered, which catches calls you didn't expect.
Checking request bodies
For mutations, test what the service sends as well as what it receives:
it('posts a new todo with completed set to false', () => {
service.addTodo('Buy milk').subscribe();
const req = httpTesting.expectOne({ method: 'POST', url: '/api/todos' });
expect(req.request.body).toEqual({ title: 'Buy milk', completed: false });
req.flush({ id: 7, title: 'Buy milk', completed: false });
});Matching on an object { method, url } is stricter than matching on a URL string. Use it when a GET and a POST share the same URL.
Simulating failures
flush accepts a status option for server errors. error simulates a network failure, which arrives as status 0.
it('gives a friendly error after retries are exhausted', () => {
let message = '';
service.getTodoSafely(1).subscribe({
error: (err: Error) => (message = err.message)
});
// retry(2) means 1 original attempt + 2 retries = 3 requests
for (let attempt = 0; attempt < 3; attempt++) {
httpTesting
.expectOne('/api/todos/1')
.flush('Server down', { status: 500, statusText: 'Server Error' });
}
expect(message).toBe('Could not load the todo.');
});
it('handles a network error', () => {
let message = '';
service.getTodoSafely(1).subscribe({ error: (err: Error) => (message = err.message) });
for (let attempt = 0; attempt < 3; attempt++) {
httpTesting.expectOne('/api/todos/1').error(new ProgressEvent('error'));
}
expect(message).toBe('Could not load the todo.');
});Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| `Expected one matching request, found none` | Never subscribed, or URL/params differ | Subscribe before `expectOne`; include the query string |
| Real network calls in tests | `provideHttpClientTesting()` missing or listed first | Put it after `provideHttpClient()` |
| `Expected no open requests` | A retry or extra call was left pending | Answer every request, or match with `match()` |
| Interceptor not applied in test | Test used plain `provideHttpClient()` | Pass the same `withInterceptors([...])` you use in the app |
Exercise
Write a test that calls deleteTodo(3), checks that the request uses the DELETE method on /api/todos/3, and completes it with an empty body. What value should you pass to flush?
Show answer
Call service.deleteTodo(3).subscribe();, then const req = httpTesting.expectOne('/api/todos/3'); expect(req.request.method).toBe('DELETE'); req.flush(null);. Pass null because the endpoint returns no content and the service is typed as Observable<void>.
Exercise
A service method uses retry(1). Your test flushes one 500 response and afterEach fails with an open-request error. Why?
Show answer
retry(1) resubscribes once after the first failure, which sends a second request. That request is still pending. Match it with another expectOne and flush it too.