Sub topic 6
Setting up HttpClient for testing
This chapter shows how to configure TestBed so that HttpClient works in a unit test without reaching a network. It assumes you know TypeScript, Angular services and dependency injection, RxJS subscribe, the basics of HttpClient, and how to run ng test. It also assumes you have used TestBed.inject from the previous chapters. The next chapters cover matching requests and sending responses in detail. Here the goal is a correct, minimal setup and an understanding of why it works.
Why HttpClient needs special setup
HttpClient does not send requests itself. It builds an HttpRequest, passes it through any interceptors, and hands it to an HttpBackend. The backend is the part that talks to the network. In an application the backend is HttpXhrBackend, or FetchBackend if you enable withFetch().
A unit test should not use either one:
- A real request needs a running server, which makes the test slow and fragile.
- The test could not control the response, so it could not check error handling or retries.
- A test that depends on the network can pass or fail for reasons unrelated to your code.
Angular solves this by letting you replace the backend. provideHttpClientTesting() registers a testing backend that records every request in memory and never sends it. Your test then answers each recorded request through HttpTestingController.
The diagram shows two things that matter later. Interceptors still run, so a test sees the request after they have modified it. The service code is unchanged, because it keeps calling HttpClient as usual.
The two providers
The setup uses two provider functions from two different entry points:
| Function | Import from | Role |
|---|---|---|
| `provideHttpClient()` | `@angular/common/http` | Registers `HttpClient` and the normal request pipeline |
| `provideHttpClientTesting()` | `@angular/common/http/testing` | Replaces the backend with the testing backend and registers `HttpTestingController` |
You need both. provideHttpClientTesting() only swaps the backend. It does not register HttpClient itself, so using it alone leaves your service without an HttpClient to inject.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
describe('UserService setup', () => {
let service: UserService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserService);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('creates the service', () => {
expect(service).toBeTruthy();
});
});This example uses UserService from the earlier chapter. It is providedIn: 'root', so TestBed can create it without you listing it in providers.
Why the order matters
Put provideHttpClient() first and provideHttpClientTesting() second. Providers later in the list override earlier ones for the same token, and the testing function overrides the backend that provideHttpClient() registered. If you reverse them, the real backend can replace the testing backend and your test may attempt a real request. Keep the pair together in this order every time.
Injecting what you need
Each test file usually needs two objects:
- The service under test, from
TestBed.inject(UserService). - The controller, from
TestBed.inject(HttpTestingController).
The controller is a singleton inside the TestBed injector. The service's HttpClient and the controller share the same testing backend, so a request sent by the service shows up on the controller you injected. You do not wire them together yourself.
You can also inject HttpClient directly when you test something that is not a service, such as an interceptor, as shown at the end of this chapter:
const http = TestBed.inject(HttpClient);Create objects after configuring
TestBed.configureTestingModule must run before the first TestBed.inject. The first inject call creates the test injector and freezes the configuration. Calling configureTestingModule afterward in the same test throws an error. Put configuration in beforeEach, and never at the top of the describe callback.
TestBed resets between tests. Each it block gets a fresh injector, a fresh service instance, and a fresh controller. State from one test, such as a pending request, cannot leak into the next.
The verify call in afterEach
httpTesting.verify() in afterEach is part of the setup, not an optional extra. It throws if any request was sent but never matched by expectOne or similar methods. Without it, a service that makes an unexpected extra request would pass silently. The chapter on verify covers this in depth. For now, add it to every test file that uses the controller so that the habit is in place from the start.
A first request, end to end
This smoke test confirms your setup works. It sends one request, finds it, and answers it. The later chapters explain expectOne and flush fully.
it('sends a GET request that the testing backend captures', () => {
let result: User | undefined;
service.getUser(1).subscribe((user) => (result = user));
const req = httpTesting.expectOne('/api/users/1');
req.flush({ id: 1, name: 'Ada' });
expect(result).toEqual({ id: 1, name: 'Ada' });
});Note the order of events. The service's get call does not run until subscribe is called, because HttpClient observables are cold. Only after the subscription does the testing backend record the request. If you call expectOne before subscribing, it fails because no request exists yet.
Setup variants
Configuring interceptors
To test with interceptors, pass them to provideHttpClient through withInterceptors. Features go inside the provideHttpClient call, and the testing provider stays after it:
import {
HttpClient,
HttpInterceptorFn,
provideHttpClient,
withInterceptors,
} from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
const addHeader: HttpInterceptorFn = (req, next) =>
next(req.clone({ setHeaders: { 'X-Test': 'on' } }));
describe('interceptor setup', () => {
it('runs the interceptor before the testing backend', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([addHeader])),
provideHttpClientTesting(),
],
});
TestBed.inject(HttpClient).get('/api/ping').subscribe();
const httpTesting = TestBed.inject(HttpTestingController);
const req = httpTesting.expectOne('/api/ping');
expect(req.request.headers.get('X-Test')).toBe('on');
req.flush({});
httpTesting.verify();
});
});The request you inspect is the one the backend received, so it includes the header added by the interceptor.
Decide per test file whether to include interceptors. If you test a service, you usually leave them out. The service test then checks only what the service sends, and a separate test file checks each interceptor. Registering your whole production interceptor chain in every service test couples unrelated tests: a change to the auth interceptor could break dozens of service tests.
Using the real application config
You can reuse appConfig.providers in a test, but this is rarely a good idea. It brings in the router, the production interceptors, and anything else the app registers, and it may include a real backend. If you must reuse it, add provideHttpClientTesting() last so that it overrides the backend.
The legacy module
Older code uses HttpClientModule and HttpClientTestingModule:
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
});This still works in code you maintain, but the module-based API is deprecated in recent Angular versions. Prefer the two provider functions for new tests. If you see both styles in the same project, do not mix them inside one TestBed configuration.
Common setup errors
| Symptom | Cause | Fix |
|---|---|---|
| `NullInjectorError: No provider for HttpClient` | `provideHttpClient()` is missing | Add `provideHttpClient()` before `provideHttpClientTesting()` |
| `NullInjectorError: No provider for HttpTestingController` | `provideHttpClientTesting()` is missing | Add it after `provideHttpClient()` |
| `expectOne` fails with "Expected one matching request, found none" | The observable was never subscribed to, or the URL differs | Subscribe first, and compare the full URL |
| Real network errors or timeouts in a test | Providers in the wrong order, or the testing provider is missing | Put `provideHttpClientTesting()` last |
| A test fails in `afterEach` with an open-request message | The service sent a request the test never answered | Answer it with `flush`, or fix the service |
| `Cannot configure the test module when the test module has already been instantiated` | `configureTestingModule` ran after `TestBed.inject` | Configure once, in `beforeEach`, before injecting |
Summary of the setup rules
- Register
provideHttpClient()and thenprovideHttpClientTesting(). - Add interceptors with
withInterceptorsinsideprovideHttpClient, only when the test is about them. - Configure
TestBedinbeforeEach, then inject the service and the controller. - Call
verify()inafterEach. - Subscribe before looking for a request, because the observable is cold.
Exercise
A teammate writes this configuration and the test throws a real network error instead of using the testing backend. Name two things that could cause it, and give the corrected providers array. providers: [provideHttpClientTesting(), provideHttpClient()]
Show answer
The testing provider is listed before provideHttpClient(), so the later provider replaces the testing backend with the real one and the request goes to the network. A related cause is leaving provideHttpClientTesting() out entirely. The corrected array is: providers: [provideHttpClient(), provideHttpClientTesting()]
Exercise
A test calls httpTesting.expectOne('/api/users/1') and fails with "found none", although the service method calls this.http.get('/api/users/1'). The test never subscribes to the returned observable. What is wrong, and how do you fix the test?
Show answer
HttpClient observables are cold, so no request is made until something subscribes. The test must call service.getUser(1).subscribe(...) before calling expectOne. After that, the testing backend records the request and expectOne finds it.