Sub topic 13
Testing functional interceptors
This chapter assumes you can write a functional interceptor, know how provideHttpClient is configured, and have read the earlier chapters on TestBed and HttpTestingController. It shows two ways to test an interceptor, what each one proves, and the mistakes that make interceptor tests pass for the wrong reasons.
What an interceptor test should prove
A functional interceptor is a function of type HttpInterceptorFn. It receives a request and a next function, and it returns an Observable of events. It can change the request on the way out, change the response or error on the way back, or both.
Test the behavior the interceptor owns:
- Which requests it changes, and which it leaves alone.
- What it adds or removes, such as headers or the URL.
- What it does with errors, such as calling a service or rethrowing.
Do not test that HttpClient works or that headers are serialized. Those belong to Angular.
Approach 1: through HttpClient
This approach builds the real interceptor chain and replaces only the network. The interceptor is registered with withInterceptors, and provideHttpClientTesting() supplies the backend at the end of the chain. HttpTestingController therefore sees each request after every interceptor has run.
import {
HttpClient,
HttpInterceptorFn,
provideHttpClient,
withInterceptors,
} from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
export const authInterceptor: HttpInterceptorFn = (req, next) =>
next(req.clone({ setHeaders: { Authorization: 'Bearer test-token' } }));
describe('authInterceptor through HttpClient', () => {
let http: HttpClient;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),
],
});
http = TestBed.inject(HttpClient);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('adds the Authorization header', () => {
http.get('/api/ping').subscribe();
const req = httpTesting.expectOne('/api/ping');
expect(req.request.headers.get('Authorization')).toBe('Bearer test-token');
req.flush({});
});
});Two details matter here.
- Order of providers. Put
provideHttpClientTesting()afterprovideHttpClient(...). Both providers set theHttpBackend, and the later one wins. If the order is reversed, the real XHR backend can replace the testing backend, and requests may leave the test. - Which request you inspect. Requests are immutable.
req.clone(...)creates a new object, so the request your test passes tohttp.getis not the one that was modified. Always assert onreq.requestfromexpectOne, which is the request as the backend received it.
Approach 2: calling the function directly
An HttpInterceptorFn is a plain function, so you can call it yourself with a hand-made request and a fake next. This isolates the interceptor from HttpClient, the interceptor chain, and the controller.
The interceptor may call inject(), which only works in an injection context. TestBed.runInInjectionContext provides one.
import {
HttpHandlerFn,
HttpRequest,
HttpResponse,
} from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
describe('authInterceptor called directly', () => {
it('forwards a clone with the Authorization header', () => {
const original = new HttpRequest('GET', '/api/ping');
let forwarded: HttpRequest<unknown> | undefined;
const next: HttpHandlerFn = (request) => {
forwarded = request;
return of(new HttpResponse({ status: 200 }));
};
TestBed.runInInjectionContext(() =>
authInterceptor(original, next),
).subscribe();
expect(forwarded?.headers.get('Authorization')).toBe('Bearer test-token');
expect(original.headers.has('Authorization')).toBe(false);
});
});The last assertion checks that the original request was not mutated. That check is only possible with a direct call.
Choosing between the two
| Question | Through HttpClient | Direct call |
|---|---|---|
| Tests the real interceptor chain and ordering | Yes | No |
| Needs `HttpTestingController` | Yes | No |
| Controls `next` exactly (delay, error, no emission) | Limited, via `flush` and `error` | Fully |
| Catches a missing `withInterceptors` registration | Yes | No |
| Speed and setup size | More setup | Less setup |
A practical split is to use the direct call for branch-heavy logic and to keep one or two HttpClient tests per interceptor. Those tests confirm that it is registered and runs in the right place.
Interceptors that depend on other services
Interceptors often call inject() for a token store, a router, or a session service. Replace those dependencies with providers, as in the earlier chapter on stubs. The next example is an interceptor that signs the user out when the server answers 401:
import {
HttpErrorResponse,
HttpInterceptorFn,
} from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, throwError } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class SessionService {
signOut(): void {
// clears stored credentials in the real application
}
}
export const unauthorizedInterceptor: HttpInterceptorFn = (req, next) => {
const session = inject(SessionService);
return next(req).pipe(
catchError((error: unknown) => {
if (error instanceof HttpErrorResponse && error.status === 401) {
session.signOut();
}
return throwError(() => error);
}),
);
};The test replaces SessionService with an object that counts calls. It uses no spy library, so it works with Jasmine or Jest.
import {
HttpClient,
HttpErrorResponse,
provideHttpClient,
withInterceptors,
} from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
describe('unauthorizedInterceptor', () => {
let http: HttpClient;
let httpTesting: HttpTestingController;
let signOutCalls: number;
beforeEach(() => {
signOutCalls = 0;
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([unauthorizedInterceptor])),
provideHttpClientTesting(),
{
provide: SessionService,
useValue: { signOut: () => signOutCalls++ },
},
],
});
http = TestBed.inject(HttpClient);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('signs out on 401 and still delivers the error', () => {
let status: number | undefined;
http.get('/api/me').subscribe({
error: (e: HttpErrorResponse) => (status = e.status),
});
httpTesting
.expectOne('/api/me')
.flush('denied', { status: 401, statusText: 'Unauthorized' });
expect(signOutCalls).toBe(1);
expect(status).toBe(401);
});
it('does not sign out on other errors', () => {
http.get('/api/me').subscribe({ error: () => {} });
httpTesting
.expectOne('/api/me')
.flush('boom', { status: 500, statusText: 'Server Error' });
expect(signOutCalls).toBe(0);
});
it('does not sign out on success', () => {
http.get('/api/me').subscribe();
httpTesting.expectOne('/api/me').flush({ id: 1 });
expect(signOutCalls).toBe(0);
});
});The three tests cover the branch that triggers the side effect and the two branches that must not. They also check that the error still reaches the subscriber, which is the part of an error interceptor that is easiest to break.
Testing more than one interceptor
withInterceptors([a, b]) runs a first on the request and b second. On the response, the order is reversed. If order matters, for example one interceptor adds a header and another reads it, register both and assert on the final request:
const addTrace: HttpInterceptorFn = (req, next) =>
next(req.clone({ setHeaders: { 'X-Trace': 'abc' } }));
const copyTrace: HttpInterceptorFn = (req, next) =>
next(
req.clone({
setHeaders: { 'X-Trace-Copy': req.headers.get('X-Trace') ?? 'missing' },
}),
);
it('runs interceptors in registration order', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([addTrace, copyTrace])),
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-Trace-Copy')).toBe('abc');
req.flush({});
httpTesting.verify();
});Swapping the array order makes the copied value missing, so the test fails when someone reorders the interceptors.
Common mistakes
- Testing the interceptor without registering it. If
provideHttpClient()is called withoutwithInterceptors, requests go through unchanged. The test then fails with a missing header, which looks like a bug in the interceptor when it is a setup problem. - Asserting on the wrong request object. The request you passed to
http.getis not the modified one. Usereq.request. - Skipping
verify(). An interceptor that retries or issues extra requests produces stray requests that onlyhttpTesting.verify()reports. - Forgetting to flush. An interceptor's
pipelogic, such ascatchError, runs only after a response or error arrives. Without aflushorerror, the test checks nothing about the response path. - Mixing up
flushanderror.flushwith a non-2xx status becomes anHttpErrorResponsewith that status.error(new ProgressEvent('error'))simulates a network failure with status 0. An interceptor that branches onstatus === 0needs the second form. - Stubbing too much. If you stub every dependency in a direct-call test, you may only confirm your stubs. Keep at least one
HttpClienttest per interceptor.
Exercises
Exercise
A test registers provideHttpClientTesting() first and provideHttpClient(withInterceptors([authInterceptor])) second. Why is this risky, and what is the correct order?
Show answer
Both providers set the HttpBackend, and the later one wins. With this order the real backend can replace the testing backend, so requests may reach the network and HttpTestingController may see nothing. Put provideHttpClient(...) first and provideHttpClientTesting() after it.
Exercise
An interceptor adds Authorization to every request whose URL starts with /api/. Name three tests that cover its behavior.
Show answer
(1) A request to /api/ping has the header, asserted on req.request.headers from expectOne. (2) A request to a non-API URL such as /assets/logo.svg does not have the header. (3) The original HttpRequest is not mutated, which a direct-call test with runInInjectionContext and a fake next can check.
Exercise
In the 401 interceptor test, why does the first test also assert that status is 401 after checking signOutCalls?
Show answer
The interceptor must run its side effect and still rethrow the error. If it swallowed the error, signOutCalls would still be 1, but the subscriber would never receive the 401. The status assertion catches that bug.