Sub topic 12
Testing an Interceptor with HttpTestingController
This chapter shows how to unit test a functional interceptor without a real server. It assumes you know TypeScript, Angular dependency injection, HttpClient GET and POST calls, and basic RxJS. It also assumes you have written the authInterceptor from the earlier chapter on attaching an authorization header.
Why test interceptors separately
An interceptor runs on every request, so a bug in it affects the whole application. A missing next(req) call stops all traffic. A wrong header leaks a token or breaks every API call. These bugs are hard to spot by clicking through the UI, and a unit test catches them cheaply.
You do not call the interceptor function directly. It needs a next function and an injection context, and you want to see how it behaves inside the real chain. Instead, you register it with provideHttpClient, make a request through HttpClient, and replace the network with a test backend.
The pieces of the test setup
Three pieces work together.
provideHttpClient(withInterceptors([...]))is the same registration you use in the application. The interceptor under test runs in its real position in the chain.provideHttpClientTesting()replaces the browser HTTP backend with a test backend. No request leaves the test process.HttpTestingControlleris the handle for that test backend. It records each outgoing request so you can inspect it and answer it.
Order matters here. Call provideHttpClientTesting() after provideHttpClient(...), so the testing backend replaces the real one.
A first test: the header is added
The following test checks that authInterceptor adds the Authorization header. It stubs AuthService so the test controls the token.
import { TestBed } from '@angular/core/testing';
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { authInterceptor } from './auth.interceptor';
import { AuthService } from './auth.service';
describe('authInterceptor', () => {
it('adds the Authorization header', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),
{ provide: AuthService, useValue: { getToken: () => 'abc' } },
],
});
const http = TestBed.inject(HttpClient);
const controller = TestBed.inject(HttpTestingController);
http.get('/api/data').subscribe();
const req = controller.expectOne('/api/data');
expect(req.request.headers.get('Authorization')).toBe('Bearer abc');
req.flush({});
controller.verify();
});
});Walk through it step by step.
TestBed.configureTestingModuleregisters the interceptor, the testing backend, and a fakeAuthService. The interceptor callsinject(AuthService), so it receives the stub.http.get('/api/data').subscribe()starts the request.HttpClientobservables are cold, so nothing is sent until you subscribe.controller.expectOne('/api/data')finds the one pending request with that URL. It fails the test if there are zero matches or more than one. It returns aTestRequest.req.requestis theHttpRequestas the backend received it, after the interceptor changed it. The assertion reads the header from that object.req.flush({})completes the request with a fake body. Without it, the observable never emits.controller.verify()fails the test if any request is still unanswered or any unexpected request was made.
Matching requests
expectOne accepts several forms. Pick the one that expresses what you want to check.
| Form | Matches | Use it when |
|---|---|---|
| `expectOne('/api/data')` | A URL string, including query parameters (`urlWithParams`) | You know the exact URL |
| `expectOne({ method: 'POST', url: '/api/data' })` | Method and URL together | The same URL is used with different methods |
| `expectOne(req => req.headers.has('Authorization'))` | A predicate on `HttpRequest` | You want to select by a property such as a header |
| `match(...)` | Zero or more requests | Several requests are expected, or none |
| `expectNone(...)` | No request | You assert that something was not sent |
A URL with query parameters must be written in full, for example '/api/data?page=2'. If a test cannot find a request that you know was made, compare the string with req.urlWithParams.
Testing the branch with no token
A good interceptor test covers each branch. The authInterceptor forwards the original request when there is no token. Test that case with a different stub.
import { TestBed } from '@angular/core/testing';
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { authInterceptor } from './auth.interceptor';
import { AuthService } from './auth.service';
describe('authInterceptor without a token', () => {
it('does not add an Authorization header', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),
{ provide: AuthService, useValue: { getToken: () => null } },
],
});
const http = TestBed.inject(HttpClient);
const controller = TestBed.inject(HttpTestingController);
http.get('/api/data').subscribe();
const req = controller.expectOne('/api/data');
expect(req.request.headers.has('Authorization')).toBe(false);
req.flush({});
controller.verify();
});
});In a larger suite, move the shared setup into a beforeEach and let each test change only the stub. A mutable stub object keeps this short: create const auth = { getToken: () => 'abc' as string | null };, provide it with useValue: auth, and reassign auth.getToken inside a test.
Testing response and error behavior
Interceptors that change responses or handle errors need a fake answer, not only an inspection. TestRequest has two methods for this.
flush(body, opts?)answers with a body. To simulate a non-2xx status, pass{ status: 401, statusText: 'Unauthorized' }in the second argument. Angular then delivers anHttpErrorResponse.error(errorEvent, opts?)simulates a network failure. The resultingHttpErrorResponsehasstatus0.
The errorInterceptor from the error handling chapter logs and rethrows. A test can confirm that the caller still receives the error.
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { errorInterceptor } from './error.interceptor';
describe('errorInterceptor', () => {
it('rethrows server errors to the caller', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([errorInterceptor])),
provideHttpClientTesting(),
],
});
const http = TestBed.inject(HttpClient);
const controller = TestBed.inject(HttpTestingController);
const consoleSpy = spyOn(console, 'error');
let caught: HttpErrorResponse | undefined;
http.get('/api/data').subscribe({ error: (e) => (caught = e) });
controller
.expectOne('/api/data')
.flush('boom', { status: 500, statusText: 'Server Error' });
expect(caught?.status).toBe(500);
expect(consoleSpy).toHaveBeenCalled();
controller.verify();
});
});The test checks two things. The interceptor reported the error through console.error, and the subscriber still received the HttpErrorResponse. The second check protects against an interceptor that swallows errors by mistake.
The spyOn function here is Jasmine's, which is the default in Angular CLI projects. With Jest, use jest.spyOn(console, 'error').mockImplementation() instead.
Testing with several interceptors
To test order, register the real chain, or two small test interceptors, and check the combined result. Because the backend sees the request after every interceptor has run, one assertion on req.request covers the whole chain. For response order, flush a response and record what each interceptor does on the way back, for example by pushing names into an array from tap.
Common mistakes in interceptor tests
- Forgetting
subscribe(). The request is never sent, soexpectOnefails with "Expected one matching request... found none". - Forgetting
flush(). The subscriber never receives a value.verify()then fails because a request is still open. - Registering the testing provider before the client provider. The real backend can replace the test backend. Keep
provideHttpClientTesting()afterprovideHttpClient(...). - Using a real
AuthService. The test then depends on browser storage or other services. Stub it withuseValue. - Skipping
verify(). Without it, a request that your code sends by accident goes unnoticed. - Asserting on the wrong object. Read headers from
req.request, which is the request as it arrived at the backend.
Exercise
You wrote a test for authInterceptor that calls http.get('/api/data').subscribe() and then controller.expectOne('/api/data'), but you see the assertion expect(req.request.headers.get('Authorization')).toBe('Bearer abc') pass while controller.verify() fails with "Expected no open requests, found 1". What is missing, and why does verify() fail?
Show answer
The test never calls req.flush(...) (or req.error(...)) on the matched request. The assertion passes because the interceptor already ran and the request reached the testing backend. The request is still open because no response was supplied, so verify() reports one open request. Adding req.flush({}) before controller.verify() completes it.
Exercise
Write the arguments you would pass to flush to make a request fail with status 401, and name the type of error the subscriber receives.
Show answer
req.flush('Unauthorized', { status: 401, statusText: 'Unauthorized' }). The subscriber's error callback receives an HttpErrorResponse whose status is 401.
Exercise
Why can you use a single expectOne call to check the combined effect of several interceptors?
Show answer
The testing backend sits at the end of the chain. By the time a request reaches it, every interceptor has already run in order, so req.request shows the final result of all their changes.