Sub topic 4
Replacing dependencies with stubs
This chapter assumes you can write an Angular service that uses inject(). It also assumes you know the basics of TestBed from the previous chapter. You will replace a real dependency with a small fake, so the test exercises only the service under test.
Why stub a dependency
A service often calls another service. If the test uses the real one, the result depends on code you are not testing. A failure in the dependency then shows up as a failure in your service. A stub is a simple object with the same shape as the dependency and a fixed behavior. It gives you three things:
- Control: you choose what the dependency returns.
- Isolation: a bug in the dependency cannot break this test.
- Speed: no real work, storage, or network access happens.
How a provider override works
TestBed builds its own injector for each test. When you list a provider in configureTestingModule, it takes priority over the one declared with providedIn: 'root'. The service under test asks for the dependency by its class, the injector finds your provider, and the stub is returned.
A worked example
AuthHeaderService builds an Authorization header from a token held by TokenStore. The test replaces TokenStore with an object literal.
import { Injectable, inject } from '@angular/core';
import { TestBed } from '@angular/core/testing';
@Injectable({ providedIn: 'root' })
export class TokenStore {
token(): string {
return 'real-token';
}
}
@Injectable({ providedIn: 'root' })
export class AuthHeaderService {
private readonly store = inject(TokenStore);
header(): string {
return `Bearer ${this.store.token()}`;
}
}
describe('AuthHeaderService', () => {
it('builds the header from the stubbed token', () => {
TestBed.configureTestingModule({
providers: [{ provide: TokenStore, useValue: { token: () => 'stub-token' } }],
});
const service = TestBed.inject(AuthHeaderService);
expect(service.header()).toBe('Bearer stub-token');
});
});The provider { provide: TokenStore, useValue: ... } means: "when anyone asks for TokenStore, hand out this exact value." The stub is not an instance of TokenStore. That is fine, because TypeScript only checks the object where you write it, and the injector does not check types at runtime.
Recording what the service did
A stub can also record calls, so you can assert that the service used it correctly. This example uses only plain TypeScript, so it works with any test runner.
const calls: string[] = [];
const stub = {
token: () => {
calls.push('token');
return 'stub-token';
},
};
TestBed.configureTestingModule({
providers: [{ provide: TokenStore, useValue: stub }],
});
TestBed.inject(AuthHeaderService).header();
expect(calls).toEqual(['token']);Your test framework's spy helpers do the same job with less code. Use them if your project already does.
Choosing the right kind of provider
| Provider form | Use it when |
|---|---|
| `useValue` | The stub is a ready-made object. This is the most common case. |
| `useClass` | The stub needs its own state or several methods, so a small class is clearer. |
| `useFactory` | The stub must be built at injection time, for example from another injected value. |
Keeping stubs honest
A stub only has the methods you wrote, so a typo in the stub can hide a real bug. Reduce that risk in these ways:
- Declare the stub with a type, for example
const stub: Pick<TokenStore, 'token'> = { token: () => 'stub-token' };. The compiler then flags a wrong method name or return type. - Stub only what the service under test actually calls.
- Do not stub the service you are testing. Stub its collaborators.
Exercise
A ReportService injects a Clock class with a now(): number method. You want the test to be deterministic. Write the provider you would pass to configureTestingModule, and say why the stub does not have to be an instance of Clock.
Show answer
Use providers: [{ provide: Clock, useValue: { now: () => 1000 } }]. The injector matches providers by the Clock token, not by the type of the value. It hands the object to any code that asks for Clock, and the service only needs the now method to exist at runtime.