Sub topic 9
Testing HTTP calls
Components and services that call a backend are hard to test if every test needs a live server. Angular avoids this with HttpTestingController. It replaces the network layer, so your test can see each request, answer it with data of your choosing, and check that nothing unexpected was sent. This chapter covers that workflow, including error responses and a component that loads data over HTTP.
Prerequisites: you can write a basic Vitest test with describe, it, and expect, and you know TestBed and ComponentFixture from earlier chapters. You also know what HttpClient returns (a cold observable) and how toSignal works.
How the testing backend works
In a normal app, provideHttpClient() wires HttpClient to a backend that uses the browser's fetch or XMLHttpRequest. In a test, provideHttpClientTesting() swaps that backend for an in-memory one. Nothing goes over the network. Each request is held in a list until the test looks at it and answers it.
Two details follow from this model:
HttpClientis lazy. No request exists until something subscribes, soexpectOnebeforesubscribefails.- The response is delivered synchronously inside
flush. You don't needawaitor fake timers for HTTP itself.
Setting up the providers
Register both providers in the testing module:
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});List provideHttpClient() first. provideHttpClientTesting() overrides the backend, and the order makes sure the override is the one that stays. If you only provide the testing function, HttpClient may not be available at all.
Interceptors you add with provideHttpClient(withInterceptors([...])) still run in tests. That is useful when you want to test an auth interceptor. It also means your interceptor can change the URL or headers you see in expectOne.
Your first HTTP test
This test uses the UserService from the chapter's example code, which calls GET /api/users.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { afterEach, beforeEach, describe, it, expect } from 'vitest';
import { UserService } from './user-list.component';
describe('UserService', () => {
let service: UserService;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserService);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => {
http.verify();
});
it('requests the user list with GET', () => {
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']);
});
});The steps are always the same:
- Call the code under test and subscribe.
- Use
expectOneto find the pending request. It returns aTestRequest. - Assert on
req.request: method, URL, headers, params, body. - Call
req.flush(body)to answer. The subscriber runs now. - Assert on what the subscriber received.
Putting http.verify() in afterEach means every test in the file gets the check automatically.
Finding requests: expectOne, match, and none
expectOne is strict. It throws if zero requests match or if more than one does. That strictness catches bugs such as a service that sends the same request twice.
| Method | Returns | Fails when |
|---|---|---|
| `expectOne(urlOrMatcher)` | One `TestRequest` | Zero or more than one request matches |
| `match(urlOrMatcher)` | Array of `TestRequest` (may be empty) | Never |
| `expectNone(urlOrMatcher)` | Nothing | At least one request matches |
| `verify()` | Nothing | Any request is still unanswered |
A string argument is compared with the request's urlWithParams, so '/api/users' does not match /api/users?page=2. For anything more specific, pass a predicate:
const req = http.expectOne(
(r) => r.url === '/api/users' && r.params.get('page') === '2',
);You can also pass { method: 'POST', url: '/api/users' } to match on method and URL together. Use match when you expect several calls, for example a refresh button clicked twice. Use expectNone to prove that something did not call the server, such as a cached value being reused.
Checking the request body
For a POST or PUT, assert on req.request.body before you flush:
it('sends the new user in the body', () => {
service.create('Grace').subscribe();
const req = http.expectOne({ method: 'POST', url: '/api/users' });
expect(req.request.body).toEqual({ name: 'Grace' });
req.flush({ id: 7, name: 'Grace' });
});This example assumes UserService has a create(name: string) method that posts { name }. The one in this chapter's sample only has list(), so add the method if you want to run it.
Testing error responses
Real servers fail, and your code should handle it. flush accepts a second argument with status and statusText. Any status outside 200 to 299 reaches the subscriber's error callback as an HttpErrorResponse:
import { HttpErrorResponse } from '@angular/common/http';
it('passes a server error to the subscriber', () => {
let error: HttpErrorResponse | undefined;
service.list().subscribe({ error: (e: HttpErrorResponse) => (error = e) });
http
.expectOne('/api/users')
.flush('Boom', { status: 500, statusText: 'Server Error' });
expect(error?.status).toBe(500);
});A network failure, where no response arrives at all, is different. Simulate it with req.error(...):
it('reports a network failure with status 0', () => {
let error: HttpErrorResponse | undefined;
service.list().subscribe({ error: (e: HttpErrorResponse) => (error = e) });
http.expectOne('/api/users').error(new ProgressEvent('error'));
expect(error?.status).toBe(0);
});Status 0 is how Angular marks "the request never got a response". Code that retries on network errors but not on 4xx errors needs both tests.
Testing a component that loads data
You can test a component's HTTP behavior without mocking the service. Provide the testing backend and let the real UserService run. This checks the whole path from request to rendered list.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { afterEach, describe, it, expect } from 'vitest';
import { UserListComponent } from './user-list.component';
describe('UserListComponent over HTTP', () => {
afterEach(() => {
TestBed.inject(HttpTestingController).verify();
});
it('renders users after the response arrives', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const fixture = TestBed.createComponent(UserListComponent);
const http = TestBed.inject(HttpTestingController);
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('li').length).toBe(0);
http.expectOne('/api/users').flush(['Ada', 'Grace']);
fixture.detectChanges();
const items = Array.from<HTMLElement>(
fixture.nativeElement.querySelectorAll('li'),
).map((li) => li.textContent);
expect(items).toEqual(['Ada', 'Grace']);
});
});The toSignal call in the component subscribes when the component is constructed, so the request is already pending right after createComponent. The test checks the empty state first, because the signal starts at initialValue. After flush, the signal holds the new array. The view only updates once you call fixture.detectChanges() again.
Choosing between a mock and the testing backend
Both techniques are valid. They test different things.
- Mock the service with
useValue(see the mocking chapter) when the component's logic is the subject. The test is shorter and doesn't care which URL the service uses. - Use
HttpTestingControllerwhen the service's request is the subject, or when you want a component test to cover the service as well. The test then breaks if someone changes the URL or method, which is what you want.
A common split is one thorough service test per endpoint, plus component tests that mock the service.
Common errors
- "Expected one matching request... found none." The code never subscribed, the URL differs (check query strings), or an interceptor rewrote it. Print the pending requests with
http.match(() => true). - "Expected one matching request... found 2." The code sent the request twice. Fix the code, or use
matchif two calls are intended. verify()fails with open requests. Flush every request the code makes, or the test has more work than it asked about.NullInjectorError: No provider for HttpClient. You forgotprovideHttpClient()inconfigureTestingModule.- The DOM didn't change after
flush. Callfixture.detectChanges(). The data has arrived, but the view hasn't rendered.
Exercise
A service method search(term) calls GET /api/users?q=<term>. Your test calls http.expectOne('/api/users') and fails with "found none". What is the cause and how do you fix it?
Show answer
A string passed to expectOne is compared with the full URL including the query string, which is /api/users?q=ada. Either pass the full string '/api/users?q=ada', or use a predicate such as (r) => r.url === '/api/users' && r.params.get('q') === 'ada'.
Exercise
Write the lines that make a subscriber receive an HttpErrorResponse with status 404 from a pending GET /api/users/9 request, assuming http is the HttpTestingController.
Show answer
http.expectOne('/api/users/9').flush('Not found', { status: 404, statusText: 'Not Found' }); Any status outside 200 to 299 goes to the subscriber's error callback.