Sub topic 7
Intercepting requests with HttpTestingController
This chapter assumes you can write a basic Angular service that uses HttpClient, that you know how TestBed provides and injects services, and that you can subscribe to an RxJS Observable. It covers how HttpTestingController captures requests and how you select the one you want. The next chapters cover checking request contents and answering requests.
Why a test backend exists
HttpClient does not open sockets itself. It builds an HttpRequest, runs it through the interceptors, and hands it to an HttpBackend, which performs the I/O. In production the backend uses fetch or XMLHttpRequest.
provideHttpClientTesting() replaces that backend with a test backend. The test backend does not send anything. It stores each request in a list of open requests and waits. The test code reads that list through HttpTestingController.
Two facts follow from this design.
- Requests exist only after something subscribes.
HttpClientObservables are cold, so callingservice.getUser(1)without.subscribe()records nothing. - Nothing completes until you answer the request. A test that never calls
flushorerrornever sees a response in the subscriber.
Wiring up the controller
Register both providers, then inject the controller from TestBed. Order matters: provideHttpClient() comes first, and provideHttpClientTesting() second so that it overrides the real backend.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { UserService } from './user.service';
describe('UserService requests', () => {
let service: UserService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserService);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('captures a request but does not answer it on its own', () => {
let emitted = false;
service.getUser(1).subscribe(() => (emitted = true));
const req = httpTesting.expectOne('/api/users/1');
expect(emitted).toBe(false);
req.flush({ id: 1, name: 'Ada' });
expect(emitted).toBe(true);
});
});The test uses a UserService from ./user.service, the service from the earlier examples. The controller is a singleton per TestBed setup, so the service and the test share the same list of open requests.
The four ways to find a request
The controller has four methods that read the open request list.
| Method | Returns | Fails when |
|---|---|---|
| `expectOne(criteria)` | One `TestRequest` | Zero or more than one request matches |
| `match(criteria)` | An array of `TestRequest` | Never fails, and returns an empty array for no match |
| `expectNone(criteria)` | Nothing | At least one request matches |
| `verify()` | Nothing | Any request is still open |
expectOne, match and expectNone all take the same kinds of criteria. A request that a method matches is removed from the open list, so a second call with the same criteria will not see it again.
Matching by URL string
A string matches the full URL including the query string, which Angular exposes as urlWithParams. /api/users and /api/users?page=2 are different strings, and a request for the second URL does not match the first.
it('matches the query string as part of the URL', () => {
service.listUsers(2).subscribe();
httpTesting.expectNone('/api/users');
const req = httpTesting.expectOne('/api/users?page=2');
req.flush([]);
});This is the most common cause of confusing failures. If your service sets params through the params option, the test must either include them in the string or use a method that ignores them, such as a predicate.
Matching by method and URL
Passing an object lets you require an HTTP method as well. Both fields are optional, and the url field is still compared with urlWithParams.
it('distinguishes requests by method', () => {
service.getUser(1).subscribe();
const req = httpTesting.expectOne({ method: 'GET', url: '/api/users/1' });
req.flush({ id: 1, name: 'Ada' });
});Matching with a predicate
A function receives the HttpRequest and returns a boolean. Use it when the URL varies, when you care about the params object, or when you need to look at headers. The second argument is a description that appears in the failure message, so write one.
it('matches with a predicate', () => {
service.listUsers(2).subscribe();
const req = httpTesting.expectOne(
(r) =>
r.method === 'GET' &&
r.url === '/api/users' &&
r.params.get('page') === '2',
'GET /api/users with page=2',
);
req.flush([]);
});In a predicate, r.url holds the URL without params when they were passed through the params option, and r.urlWithParams holds the full one. Pick the one you mean.
You can also pass a concrete HttpRequest instance, but that requires you to rebuild every field, so it is rarely worth it.
Matching several requests with `match`
match is for code that legitimately sends more than one request, such as a service that loads two pages at once.
it('collects every request for the same endpoint', () => {
service.listUsers(1).subscribe();
service.listUsers(2).subscribe();
const requests = httpTesting.match((r) => r.url === '/api/users');
expect(requests.length).toBe(2);
requests.forEach((r) => r.flush([]));
});Because match never throws, always assert on the length. Otherwise a test that finds zero requests passes silently, since forEach over an empty array does nothing.
Using `expectNone`
expectNone asserts that a request was not made. It is useful for caching and guard logic.
it('does not send anything until subscribed', () => {
service.getUser(1); // cold Observable, no subscribe
httpTesting.expectNone('/api/users/1');
});Call it at the moment you expect the absence. A request that a later step sends is not caught by an earlier expectNone.
What failures look like
Both expectOne failures throw an error whose message names the criteria and lists what the backend did receive. This makes mismatches fast to diagnose.
- Zero matches: the message says it expected one matching request and found none. Check the URL string for missing query params or a different base path.
- Several matches: the message says it found more than one. Either the service sent duplicates, which may be a real bug, or your criteria are too broad. Switch to
matchif several requests are intended.
Synchronous timing
With the testing backend, requests normally appear in the open list as soon as subscribe runs, so expectOne right after subscribe works without fakeAsync or await. There is one exception. If a service delays the request, for example with debounceTime, switchMap from an earlier async source, or an asynchronous interceptor, the request is not in the list yet. In that case you must advance time or await before calling expectOne.
Summary of the working model
provideHttpClientTesting()swaps in a backend that records requests.- A subscription creates an open request.
expectOne,matchandexpectNoneselect from the open list by URL string, method and URL object, or predicate.- A selected
TestRequestis yours to answer. verify()inafterEachconfirms that nothing is left.
Exercise
A service method calls this.http.get('/api/search', { params: { q: 'ng' } }) and the test runs httpTesting.expectOne('/api/search'). The test fails with "found none". Why, and what are two ways to fix it?
Show answer
A string criterion is compared with the full URL including the query string, which here is /api/search?q=ng, so /api/search matches nothing. Fix it by using the full string, expectOne('/api/search?q=ng'), or by using a predicate such as expectOne((r) => r.url === '/api/search' && r.params.get('q') === 'ng'), where r.url excludes the params.
Exercise
A test calls service.listUsers(1).subscribe() and service.listUsers(2).subscribe(), then runs const reqs = httpTesting.match((r) => r.url === '/api/usrs'); (with a typo) followed by reqs.forEach((r) => r.flush([]));. The test passes. What is wrong, and how do you make it fail correctly?
Show answer
match never throws, so the typo gives an empty array and forEach does nothing. Add expect(reqs.length).toBe(2); before flushing, or use expectOne when exactly one request is expected. If verify() runs in afterEach, it also fails here, because the two real requests are still open.