Sub topic 14
Testing with TestBed and Test Doubles
Dependency injection pays off most in tests. A component or service doesn't create its own dependencies, so a test can hand it different ones. This chapter shows how to use Angular's TestBed to build a test injector, how to swap real services for test doubles, and where substitution tends to go wrong.
This chapter assumes you know Jasmine-style tests (describe, it, expect, beforeEach) as generated by the Angular CLI. It also assumes you have read the earlier chapters on provider recipes, InjectionToken, and component-scoped providers. The examples reuse CartService, Logger, APP_CONFIG, and FormDraftService from those chapters.
What TestBed Actually Is
TestBed is a test-only environment injector, built fresh for each test. When you call TestBed.configureTestingModule({ providers: [...] }), you describe the providers for that injector. Angular creates the injector lazily, the first time you call TestBed.inject() or TestBed.createComponent(). After that, the configuration is locked.
Lookups follow the same rules as in a running app:
- If a component under test has its own
providersorviewProviders, its element injector answers first. - If not, the
TestBedenvironment injector checks the providers you registered. - If neither has a provider, services marked
providedIn: 'root'are created on demand from their default definition.
The third step is easy to forget. A root-provided service you never mentioned is still the real one in your test. If it makes HTTP calls or touches localStorage, your test does too.
Testing a Service Directly
A service with no dependencies of its own needs no configuration. Ask the test injector for it:
import { TestBed } from '@angular/core/testing';
import { CartService } from './cart.service';
describe('CartService', () => {
let cart: CartService;
beforeEach(() => {
TestBed.configureTestingModule({});
cart = TestBed.inject(CartService);
});
it('starts empty and counts added items', () => {
expect(cart.count()).toBe(0);
cart.add('apple');
cart.add('pear');
expect(cart.count()).toBe(2);
});
});Angular resets TestBed before every test, so each it gets a new CartService with an empty signal. State from one test does not leak into the next.
Replacing a Dependency with a Test Double
A test double is any object that stands in for a real dependency. The common kinds are stubs (return fixed data), spies (record calls), and fakes (simplified working versions). Here is a service with two dependencies:
import { Injectable, inject } from '@angular/core';
import { CartService } from './cart.service';
import { Logger } from './logger';
@Injectable({ providedIn: 'root' })
export class OrderService {
private readonly cart = inject(CartService);
private readonly logger = inject(Logger);
checkout(): number {
const total = this.cart.count();
this.logger.log(`Checking out ${total} items`);
return total;
}
}The test replaces both dependencies with useValue providers:
import { TestBed } from '@angular/core/testing';
import { signal } from '@angular/core';
import { OrderService } from './order.service';
import { CartService } from './cart.service';
import { Logger } from './logger';
describe('OrderService', () => {
it('logs the number of items at checkout', () => {
const logger = jasmine.createSpyObj<Logger>('Logger', ['log']);
const fakeCart: Pick<CartService, 'count'> = { count: signal(2) };
TestBed.configureTestingModule({
providers: [
{ provide: Logger, useValue: logger },
{ provide: CartService, useValue: fakeCart }
]
});
const orders = TestBed.inject(OrderService);
expect(orders.checkout()).toBe(2);
expect(logger.log).toHaveBeenCalledOnceWith('Checking out 2 items');
});
});Notice two things. First, Logger is an abstract class with no providedIn, so the test must provide it. Without that provider the test fails with NG0201. Second, OrderService itself is still the real class. You replace the dependencies of the thing under test, never the thing itself.
useValue does not type-check the value against the token. TypeScript would accept { provide: CartService, useValue: 42 }. Annotating the fake with Pick<CartService, 'count'> brings type checking back. If someone renames count in the real service, the test then fails to compile instead of failing at runtime with a confusing undefined is not a function.
Choosing a provider recipe for the double
| Recipe | Use it when | Example |
|---|---|---|
| `useValue` | A plain object or spy is enough | `{ provide: Logger, useValue: spy }` |
| `useClass` | The double is a reusable class, possibly with its own `inject()` calls | `{ provide: Logger, useClass: SilentLogger }` |
| `useFactory` | The double depends on other test providers | `{ provide: Logger, useFactory: () => new FakeLogger(inject(APP_CONFIG)) }` |
| `useExisting` | You need to retrieve the same double through two tokens | `{ provide: Logger, useExisting: FakeLogger }` |
Overriding Component-Scoped Providers
The earlier chapter's EditorComponent declares providers: [FormDraftService]. That puts a provider on the component's element injector, which is checked before the TestBed injector. A test-module provider is therefore never reached:
import { TestBed } from '@angular/core/testing';
import { EditorComponent, FormDraftService } from './editor.component';
describe('EditorComponent', () => {
it('renders the draft value from its own FormDraftService', () => {
const fakeDraft: FormDraftService = { value: 'hello' };
TestBed.configureTestingModule({ imports: [EditorComponent] });
TestBed.overrideComponent(EditorComponent, {
set: { providers: [{ provide: FormDraftService, useValue: fakeDraft }] }
});
const fixture = TestBed.createComponent(EditorComponent);
fixture.detectChanges();
const input: HTMLInputElement = fixture.nativeElement.querySelector('input');
expect(input.value).toBe('hello');
});
});overrideComponent rewrites the component's metadata before Angular compiles it. Use set to replace the whole providers array, or add and remove to adjust parts of it. The same applies to viewProviders.
TestBed.overrideProvider(Token, { useValue }) is a broader tool. It replaces the provider for a token everywhere, including inside component and module metadata. It is useful when a third-party component provides something you can't reach otherwise.
Testing HTTP Without a Network
HttpClient is the dependency you'll replace most often. Angular ships a testing backend for it, so you don't write a fake by hand:
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { APP_CONFIG } from './app.config';
@Injectable({ providedIn: 'root' })
export class ProductApi {
private readonly http = inject(HttpClient);
private readonly config = inject(APP_CONFIG);
list(): Observable<string[]> {
return this.http.get<string[]>(`${this.config.apiUrl}/products`);
}
}import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { ProductApi } from './product-api.service';
import { APP_CONFIG } from './app.config';
describe('ProductApi', () => {
let api: ProductApi;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
{ provide: APP_CONFIG, useValue: { apiUrl: 'https://test.local' } }
]
});
api = TestBed.inject(ProductApi);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => httpMock.verify());
it('requests the product list from the configured URL', () => {
let result: string[] = [];
api.list().subscribe(items => (result = items));
const req = httpMock.expectOne('https://test.local/products');
expect(req.request.method).toBe('GET');
req.flush(['lamp', 'desk']);
expect(result).toEqual(['lamp', 'desk']);
});
});Order matters: provideHttpClient() must come before provideHttpClientTesting(), because the testing provider overrides the backend that the first one registers. httpMock.verify() fails the test if any request went unanswered, which catches calls you didn't expect.
Testing Functions That Call inject()
Functional guards, resolvers, and helper functions call inject() directly, so they need an injection context. TestBed.runInInjectionContext supplies one from the test injector:
import { TestBed } from '@angular/core/testing';
import { inject } from '@angular/core';
import { APP_CONFIG } from './app.config';
export function apiUrl(path: string): string {
return `${inject(APP_CONFIG).apiUrl}/${path}`;
}
describe('apiUrl', () => {
it('prefixes the configured base URL', () => {
TestBed.configureTestingModule({
providers: [{ provide: APP_CONFIG, useValue: { apiUrl: 'https://test.local' } }]
});
const url = TestBed.runInInjectionContext(() => apiUrl('orders'));
expect(url).toBe('https://test.local/orders');
});
});Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `Cannot configure the test module when the test module has already been instantiated` | `configureTestingModule` or an override ran after `TestBed.inject` or `createComponent` | Do all configuration first, usually in `beforeEach` |
| NG0201 No provider for `Logger` | The token has no `providedIn` and the test didn't provide it | Add a provider for the token |
| Fake is ignored, real service runs | The component declares the service in its own `providers` | Use `overrideComponent` or `overrideProvider` |
| NG0203 `inject()` must be called from an injection context | Class or function instantiated with `new` or called directly | Use `TestBed.inject` or `TestBed.runInInjectionContext` |
| Test makes real network calls | A root service was left unreplaced | Provide a double or use `provideHttpClientTesting()` |
Exercise
A test calls TestBed.configureTestingModule({ providers: [{ provide: FormDraftService, useValue: fake }] }) and then creates EditorComponent, whose metadata includes providers: [FormDraftService]. Which instance does inject(FormDraftService) inside the component receive, and how do you make it receive the fake?
Show answer
It receives a new real FormDraftService from the component's element injector, which is checked before the TestBed injector. To substitute the fake, call TestBed.overrideComponent(EditorComponent, { set: { providers: [{ provide: FormDraftService, useValue: fake }] } }) or TestBed.overrideProvider(FormDraftService, { useValue: fake }) before createComponent.
Exercise
This test throws an error. Why, and how do you fix it? const svc = TestBed.inject(OrderService); TestBed.configureTestingModule({ providers: [{ provide: Logger, useValue: spy }] });
Show answer
TestBed.inject creates the test injector, which locks the configuration, so the later configureTestingModule call throws "Cannot configure the test module when the test module has already been instantiated". Call configureTestingModule first, then TestBed.inject(OrderService).
Exercise
Why does annotating a fake as Pick<CartService, 'count'> help, given that useValue already accepts the object?
Show answer
useValue is typed loosely and accepts any value, so a fake with a wrong or renamed member compiles and only fails at runtime. The Pick annotation makes TypeScript check the fake against the real service's member types, so API drift shows up as a compile error.