Sub topic 7
Intercepting requests with HttpTestingController
This chapter assumes you can write an Angular service that calls HttpClient, and that you have configured TestBed with provideHttpClient() and provideHttpClientTesting(). Here you will learn what HttpTestingController does with the requests your service makes, and how to find them.
What the controller does
provideHttpClientTesting() replaces the real HTTP backend with a fake one. When your service calls http.get(...), nothing goes over the network. The fake backend records the request and waits. HttpTestingController is the object that lets your test look at those recorded requests and decide how to answer each one.
The sequence matters. The request exists only after you subscribe, because HttpClient observables are cold. If you call expectOne before subscribe, no request exists yet and the test fails.
Finding requests
The controller offers three ways to look up pending requests.
| Method | Returns | Fails when |
|---|---|---|
| `expectOne(match)` | One `TestRequest` | Zero or more than one request matches |
| `match(match)` | An array of `TestRequest` | Never fails, and the array may be empty |
| `expectNone(match)` | Nothing | At least one request matches |
The match argument can take three forms: a URL string, an object with method and url, or a predicate function that receives the HttpRequest.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
describe('UserService requests', () => {
let service: UserService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserService);
httpTesting = TestBed.inject(HttpTestingController);
});
it('finds a request by URL string', () => {
service.getUser(1).subscribe();
const req = httpTesting.expectOne('/api/users/1');
req.flush({ id: 1, name: 'Ada' });
});
it('finds a request by method and URL', () => {
service.getUser(1).subscribe();
const req = httpTesting.expectOne({ method: 'GET', url: '/api/users/1' });
req.flush({ id: 1, name: 'Ada' });
});
it('finds a request with a predicate', () => {
service.getUser(1).subscribe();
const req = httpTesting.expectOne((r) => r.url.startsWith('/api/users/'));
req.flush({ id: 1, name: 'Ada' });
});
});A string matches the full URL including the query string. A string such as '/api/users' will not match '/api/users?page=2'. Use the object form with the complete URL, or a predicate that checks r.url and r.params separately.
Using match for several requests
When a service sends several requests, expectOne throws because more than one request matches. Use match and check the count yourself.
it('sends one request per user', () => {
service.getUser(1).subscribe();
service.getUser(2).subscribe();
const requests = httpTesting.match((r) => r.url.startsWith('/api/users/'));
expect(requests.length).toBe(2);
requests[0].flush({ id: 1, name: 'Ada' });
requests[1].flush({ id: 2, name: 'Alan' });
});match also removes the matched requests from the pending list. That is why a later verify() call does not complain about them.
Asserting that nothing was sent
Use expectNone for code paths that should skip the network, such as a cached value.
it('does not call the server before subscribing', () => {
service.getUser(1);
httpTesting.expectNone('/api/users/1');
});This test passes because the observable is cold. It also documents that behavior.
The TestRequest object
Every lookup gives you a TestRequest. Its request property is the real HttpRequest, so you can read method, url, params, headers and body from it. Its flush() and error() methods answer the request. The next chapters cover both in detail.
Exercise
A test calls service.listUsers(2).subscribe() and then httpTesting.expectOne('/api/users'). The service sends GET /api/users?page=2. Why does the test fail, and how do you fix it?
Show answer
A string matcher compares against the full URL with its query string, so '/api/users' does not match '/api/users?page=2'. Pass the full URL (expectOne('/api/users?page=2')), use { method: 'GET', url: '/api/users?page=2' }, or use a predicate such as (r) => r.url === '/api/users' && r.params.get('page') === '2'.