Sub topic 14
Testing HTTP Services
This chapter assumes you know how to write Jasmine-style unit tests (describe, it, expect, spyOn), how TestBed configures providers, and how the TodoService and authInterceptor from earlier chapters work. The examples use Jasmine because it is Angular's long-standing default. With Jest or Vitest, use jest.spyOn or vi.spyOn in place of spyOn. The HTTP testing APIs are the same.
The Working Model: A Fake Backend You Control
A unit test for a data service should not reach a real server. Real servers are slow, their data changes, and they fail for reasons that have nothing to do with your code. Angular avoids this by letting you swap the part of HttpClient that actually sends requests, called the backend, for a test backend.
provideHttpClientTesting() installs that test backend. When your code calls http.get(...), nothing goes over the network. The request is recorded and stays pending. Your test then uses HttpTestingController to:
- Find the pending request (
expectOne,match,expectNone). - Check what was sent: method, URL, body and headers.
- Answer it with data (
flush) or a failure (flushwith an error status, orerror). - Confirm that no unexpected requests are left over (
verify).
All of this runs synchronously. A response is delivered the moment you call flush, so you usually don't need fakeAsync or waitForAsync.
Setting Up the Test Bed
Register both providers. Put provideHttpClient() first and provideHttpClientTesting() after it, because the testing provider overrides the real backend that provideHttpClient() sets up.
Here is a complete spec for TodoService. It covers each HTTP method, the typed response, and the request details that matter.
// 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);
});
it('sends the page as a query parameter', () => {
service.getTodos(2).subscribe();
const req = httpTesting.expectOne(
r => r.url === '/api/todos' && r.params.get('page') === '2'
);
req.flush([]);
});
it('posts a new todo with completed set to false', () => {
const created: Todo = { id: 7, title: 'Ship it', completed: false };
let result: Todo | undefined;
service.addTodo('Ship it').subscribe(todo => (result = todo));
const req = httpTesting.expectOne({ method: 'POST', url: '/api/todos' });
expect(req.request.body).toEqual({ title: 'Ship it', completed: false });
req.flush(created);
expect(result).toEqual(created);
});
it('puts the whole todo to its own URL', () => {
const todo: Todo = { id: 3, title: 'Refactor', completed: true };
service.updateTodo(todo).subscribe();
const req = httpTesting.expectOne({ method: 'PUT', url: '/api/todos/3' });
expect(req.request.body).toEqual(todo);
req.flush(todo);
});
it('deletes by id', () => {
let completed = false;
service.deleteTodo(3).subscribe({ complete: () => (completed = true) });
httpTesting.expectOne({ method: 'DELETE', url: '/api/todos/3' }).flush(null);
expect(completed).toBeTrue();
});
});Matching Requests
expectOne accepts three kinds of matcher, and each suits a different case.
| Matcher | Example | Compares against | Good for |
|---|---|---|---|
| String | `'/api/todos?page=1'` | `urlWithParams` (URL plus serialized query string) | Simple requests with few parameters |
| Object | `{ method: 'POST', url: '/api/todos' }` | method and `urlWithParams` | Checking the HTTP method in the match itself |
| Predicate | `r => r.params.get('page') === '2'` | anything on the `HttpRequest` | Many parameters, headers, or body checks |
A string matcher depends on the order in which the query parameters are serialized. If a service sets page and then sort, the string must list them in that same order. With more than one or two parameters, a predicate that checks r.params.get(...) holds up better when someone reorders the code.
The Controller and TestRequest API
| Method | What it does |
|---|---|
| `expectOne(match)` | Returns the single matching `TestRequest`. Fails if zero or more than one request match. |
| `expectNone(match)` | Fails if any request matches. Use it to prove that caching or a guard prevented a call. |
| `match(match)` | Returns every matching request as an array and never fails. Use it for polling or batches. |
| `verify()` | Fails if any request is still unhandled. Pass `{ ignoreCancelled: true }` to skip cancelled ones. |
| `req.flush(body, opts?)` | Completes the request with a body, plus an optional `status`, `statusText` and `headers`. |
| `req.error(event, opts?)` | Simulates a network-level failure. The resulting `HttpErrorResponse` has status 0. |
| `req.cancelled` | `true` if the subscriber unsubscribed before a response arrived. |
Testing Error Paths and Retries
The getTodoSafely method from the error-handling chapter retries twice and then converts the failure into a friendly Error. Two details make it testable.
First, flush with a status of 400 or higher produces an HttpErrorResponse. It does not throw inside the test.
Second, retry(2) resubscribes to the source, and every resubscription sends a brand-new HTTP request. One logical call therefore produces three requests, and the test must answer each in turn. retry without a delay resubscribes synchronously, so the next request is already pending when flush returns.
Add these tests inside the same describe block:
it('retries twice on a server error, then reports a friendly error', () => {
spyOn(console, 'error');
let message: string | undefined;
service.getTodoSafely(5).subscribe({
next: () => fail('expected an error'),
error: (err: Error) => (message = err.message)
});
for (let attempt = 0; attempt < 3; attempt++) {
httpTesting
.expectOne('/api/todos/5')
.flush('Server exploded', { status: 500, statusText: 'Internal Server Error' });
}
expect(message).toBe('Could not load the todo.');
expect(console.error).toHaveBeenCalledWith('Server returned 500:', 'Server exploded');
});
it('treats a failed connection as a network error', () => {
spyOn(console, 'error');
let message: string | undefined;
service.getTodoSafely(5).subscribe({
error: (err: Error) => (message = err.message)
});
for (let attempt = 0; attempt < 3; attempt++) {
httpTesting.expectOne('/api/todos/5').error(new ProgressEvent('error'));
}
expect(message).toBe('Could not load the todo.');
expect(console.error).toHaveBeenCalledWith('Network error:', jasmine.any(ProgressEvent));
});If you handle only two requests in the retry test, verify() in afterEach fails with a message that lists the leftover request. That failure is useful: it means the retry count in the code no longer matches what the test expects.
Testing Headers and Full Responses
To test code that uses observe: 'response', pass headers and a status in the flush options:
it('exposes the total count header', () => {
let total: string | null = null;
let status = 0;
service.getTodosWithHeaders().subscribe(response => {
total = response.headers.get('X-Total-Count');
status = response.status;
});
httpTesting
.expectOne('/api/todos')
.flush([], { status: 200, statusText: 'OK', headers: { 'X-Total-Count': '42' } });
expect(status).toBe(200);
expect(total).toBe('42');
});Testing Interceptors
Interceptors run inside HttpClient, so you test them by registering them exactly as the app does and then inspecting the request that reaches the testing backend. That request is the version after the interceptors have run, so any header an interceptor adds is visible on req.request.
// auth.interceptor.spec.ts
import { TestBed } from '@angular/core/testing';
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { authInterceptor } from './auth.interceptor';
describe('authInterceptor', () => {
let http: HttpClient;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting()
]
});
http = TestBed.inject(HttpClient);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
localStorage.removeItem('access_token');
});
it('adds a bearer token when one is stored', () => {
localStorage.setItem('access_token', 'abc123');
http.get('/api/me').subscribe();
const req = httpTesting.expectOne('/api/me');
expect(req.request.headers.get('Authorization')).toBe('Bearer abc123');
req.flush({});
});
it('sends the request unchanged when no token is stored', () => {
http.get('/api/me').subscribe();
const req = httpTesting.expectOne('/api/me');
expect(req.request.headers.has('Authorization')).toBeFalse();
req.flush({});
});
});Clean up localStorage in afterEach. Otherwise a token left over from one test changes the outcome of the next, and the results depend on the order the tests run in.
Testing a Component That Loads Data
A component built with toSignal subscribes when it is constructed, so the request is already pending once createComponent returns. Render once to see the initial value, flush, then render again.
// todo-list.component.spec.ts
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TodoListComponent } from './todo-list.component';
describe('TodoListComponent', () => {
it('shows the empty state, then the loaded todos', () => {
TestBed.configureTestingModule({
imports: [TodoListComponent],
providers: [provideHttpClient(), provideHttpClientTesting()]
});
const fixture = TestBed.createComponent(TodoListComponent);
const httpTesting = TestBed.inject(HttpTestingController);
const element: HTMLElement = fixture.nativeElement;
fixture.detectChanges();
expect(element.textContent).toContain('No todos yet.');
httpTesting
.expectOne('/api/todos?page=1')
.flush([{ id: 1, title: 'Write tests', completed: false }]);
fixture.detectChanges();
expect(element.textContent).toContain('Write tests');
httpTesting.verify();
});
});Common Errors
- "Expected one matching request, found none." This usually means nothing subscribed.
HttpClientObservables are cold: no subscription, no request. Add.subscribe()even when you don't care about the result. - Assertions that pass without checking anything. If you assert inside the
subscribecallback and never callflush, the callback never runs and the test passes vacuously. Capture the value in a variable and assert afterflush, as the examples above do. - "Expected no open requests." The code sent more requests than the test handled. Typical causes are a retry, a second subscription (for example, the
asyncpipe used twice on one Observable), or polling. - The string matcher misses because of query order. Use a predicate that reads
r.params. - Forgetting
verify(). Without it, an extra request (a sign of duplicate subscriptions) goes unnoticed. Putverify()inafterEachso it runs for every test.
Exercise
A service method uses retry(3) and the test calls expectOne once, flushing a 503 error. The test then fails in afterEach. Why, and how do you fix the test so it checks the final error?
Show answer
retry(3) resubscribes three times after the first failure, and each resubscription sends a new request. After the first flush, a second request is already pending, so verify() reports it as open. Loop four times (one original attempt plus three retries), call expectOne and flush the error on each pass, then assert on the error captured in the subscriber's error callback.
Exercise
Write the matcher and assertions for a test proving that getTodos(4) sends a GET to /api/todos with page=4, without relying on how the query string is ordered.
Show answer
Use const req = httpTesting.expectOne(r => r.method === 'GET' && r.url === '/api/todos' && r.params.get('page') === '4'); and then req.flush([]);. The predicate reads the parsed parameters through r.params, so it keeps matching even if other parameters are added or their order changes.
Exercise
A cache in TodoService should make the second call to getTodos(1) return the stored data without contacting the server. Which controller method proves that no second request was sent?
Show answer
Subscribe once and flush the first request with expectOne('/api/todos?page=1'). Then subscribe again and call httpTesting.expectNone('/api/todos?page=1'). The test fails if a second matching request appears. Keep verify() in afterEach to catch any other stray request.