Sub topic 9
Testing HTTP calls
This chapter assumes you can write a basic Vitest test with TestBed. It also assumes you know Angular dependency injection and how HttpClient returns observables.
Why not call the real server
A test that hits a real network is slow, and it can fail when the server is down. It also can't easily check what your code sent. Angular supplies HttpTestingController, which replaces the real HTTP backend. Requests never leave the test. You decide when each one is answered and with what data.
The service under test is the UserService from the previous chapter:
import { Component, inject, Injectable } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class UserService {
private readonly http = inject(HttpClient);
list() {
return this.http.get<string[]>('/api/users');
}
}
@Component({
selector: 'app-user-list',
template: `
<ul>
@for (name of names(); track name) {
<li>{{ name }}</li>
}
</ul>
`,
})
export class UserListComponent {
protected readonly names = toSignal(inject(UserService).list(), {
initialValue: [] as string[],
});
}The request flow
The test subscribes to the observable. HttpClient records the request in the testing backend instead of sending it. The test then finds the request, checks it, and answers it with flush.
Setting up the providers
Two providers are needed. provideHttpClient() makes HttpClient available. provideHttpClientTesting() swaps its backend for the testing one. Put the testing provider after the client provider.
A full test
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { describe, it, expect } from 'vitest';
import { UserService } from './user-list.component';
describe('UserService', () => {
it('requests the user list with GET', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const service = TestBed.inject(UserService);
const http = TestBed.inject(HttpTestingController);
let result: string[] | undefined;
service.list().subscribe((users) => (result = users));
const req = http.expectOne('/api/users');
expect(req.request.method).toBe('GET');
req.flush(['Ada']);
expect(result).toEqual(['Ada']);
http.verify();
});
});Step by step:
service.list().subscribe(...)starts the request. Withoutsubscribe, anHttpClientobservable sends nothing.expectOne('/api/users')finds exactly one pending request with that URL. It throws if there are none or more than one.req.requestis the realHttpRequest, so you can assert onmethod,body,headers, andparams.req.flush(['Ada'])answers the request. The subscriber runs synchronously, soresultis set on the next line.http.verify()fails the test if any request was made that you did not match.
Testing failures
Real servers fail. Use flush with a status to simulate an error response:
req.flush('Not found', { status: 404, statusText: 'Not Found' });For a network failure with no response, use req.error(new ProgressEvent('error')). Subscribe with an error callback and assert on what it receives.
Common errors
| Symptom | Likely cause |
|---|---|
| `NullInjectorError: No provider for HttpClient` | `provideHttpClient()` is missing from the test providers. |
| `Expected one matching request, found none` | The code never subscribed, or the URL differs, including query strings. |
| `Expected no open requests, found 1` | `verify()` found a request you never matched or flushed. |
| Real network call is attempted | `provideHttpClientTesting()` is missing, or listed before `provideHttpClient()`. |
Exercise
A test calls service.list() but never calls subscribe. It then runs http.expectOne('/api/users'). Why does the test fail, and what is the fix?
Show answer
HttpClient observables are cold. They send the request only when subscribed to, so the testing backend holds no request and expectOne finds none. Subscribe to the observable before calling expectOne.
Exercise
Write the line that makes a pending request req fail with a 500 status, so you can test your error handling.
Show answer
req.flush('Server error', { status: 500, statusText: 'Internal Server Error' });