Sub topic 4
Replacing dependencies with stubs
This chapter assumes you can write a basic Angular service, use inject(), and run tests with the Angular CLI. It also assumes you have seen TestBed.configureTestingModule and TestBed.inject. Examples use Jasmine, which is the Angular CLI default. Jest and Vitest have equivalent spy functions.
Why replace a dependency
A service often calls other services. If you test it with the real dependencies, a failure in a dependency fails your test too. The test may also need things you don't want, such as a real token, a clock, or a network call.
A stub is a stand-in object that answers calls with values you control. Replacing a dependency with a stub gives you three things:
- Isolation. The test fails only when the service under test is wrong.
- Control. You choose what the dependency returns, including awkward cases such as an empty token or an exception.
- Observation. If the stub records calls, you can check how the service used it.
Use a stub when the dependency is slow, nondeterministic, or has side effects, or when you need to force a state that is hard to reach. Keep the real dependency when it is a small pure class that is cheap to build. A stub for such a class adds code and can drift from the real behavior.
The service under test
The examples use two services. GreetingService depends on TokenStore.
import { Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class TokenStore {
token(): string {
return 'real-token';
}
}
@Injectable({ providedIn: 'root' })
export class GreetingService {
private readonly tokens = inject(TokenStore);
describeSession(): string {
return this.tokens.token() ? 'signed in' : 'signed out';
}
}In a real application TokenStore might read from localStorage. Here it returns a constant, which is enough to show the mechanics.
How the override works
TestBed builds a test injector from the providers you list in configureTestingModule. When GreetingService asks for TokenStore, the injector looks in that list first. A provider you list there takes precedence over the providedIn: 'root' registration on the class.
The service code does not change. Only the injector's answer changes.
Providing a stub with useValue
The simplest provider replaces the token with a ready-made object.
import { TestBed } from '@angular/core/testing';
describe('GreetingService with a stubbed TokenStore', () => {
it('reports a signed-in session when a token exists', () => {
TestBed.configureTestingModule({
providers: [{ provide: TokenStore, useValue: { token: () => 'stub-token' } }],
});
const service = TestBed.inject(GreetingService);
expect(service.describeSession()).toBe('signed in');
});
it('reports a signed-out session when the token is empty', () => {
TestBed.configureTestingModule({
providers: [{ provide: TokenStore, useValue: { token: () => '' } }],
});
const service = TestBed.inject(GreetingService);
expect(service.describeSession()).toBe('signed out');
});
});Each test configures its own module, so each test gets its own stub. TestBed resets between tests, so the first stub does not leak into the second.
provide is the injection token, here the class TokenStore. useValue is the object returned for that token. Because useValue is not type-checked against TokenStore, a stub that omits methods compiles fine. If the service later calls a method the stub lacks, you get a runtime TypeError. The section on pitfalls below covers this.
Recording calls with a spy
A plain object cannot tell you whether the service called it. A spy is a function that records its calls and returns a value you configure. jasmine.createSpyObj builds an object whose listed methods are all spies.
it('asks the token store exactly once', () => {
const tokenStore = jasmine.createSpyObj<TokenStore>('TokenStore', ['token']);
tokenStore.token.and.returnValue('abc');
TestBed.configureTestingModule({
providers: [{ provide: TokenStore, useValue: tokenStore }],
});
const service = TestBed.inject(GreetingService);
service.describeSession();
expect(tokenStore.token).toHaveBeenCalledTimes(1);
});Two points matter here. First, the generic <TokenStore> makes the compiler check that 'token' is a real method name. Second, and.returnValue sets what the spy returns, and you can change it between calls with and.returnValues or and.callFake when a test needs different answers over time.
Check calls only when the call itself is the behavior you care about. If the service must send the token to the server, asserting that token was called is useful. If the call is an incidental detail, asserting on it makes the test break on harmless refactors.
The other provider forms
useValue is not the only choice. The provider object supports three more forms, and each fits a different situation.
| Form | What it does | Use it when |
|---|---|---|
| `useValue` | Returns one existing object | The stub is a small literal or a spy object |
| `useClass` | Creates an instance of another class | The stub has several methods or some internal state |
| `useFactory` | Calls a function to build the stub | The stub depends on other injected values |
| `useExisting` | Aliases the token to another token | Two tokens must resolve to the same instance |
A fake class is worth writing when several tests need the same stub behavior.
class FakeTokenStore implements TokenStore {
current = 'fake-token';
token(): string {
return this.current;
}
}
TestBed.configureTestingModule({
providers: [{ provide: TokenStore, useClass: FakeTokenStore }],
});
const fake = TestBed.inject(TokenStore) as unknown as FakeTokenStore;
fake.current = '';
expect(TestBed.inject(GreetingService).describeSession()).toBe('signed out');implements TokenStore makes the compiler warn you when the real class gains a method your fake lacks. This is the main advantage of a fake class over an object literal. The cast is needed because TestBed.inject(TokenStore) is typed as the real class, while the instance is the fake.
Changing a provider after configuration
Sometimes the module is configured in a shared beforeEach, and one test needs a different stub. TestBed.overrideProvider handles this, but it must run before the first TestBed.inject call in that test.
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{ provide: TokenStore, useValue: { token: () => 'default' } }],
});
});
it('handles an empty token', () => {
TestBed.overrideProvider(TokenStore, { useValue: { token: () => '' } });
expect(TestBed.inject(GreetingService).describeSession()).toBe('signed out');
});Once TestBed has created an injector, the configuration is frozen. Calling configureTestingModule or overrideProvider after an inject call throws an error.
Pitfalls
- Partial stubs hide breakage. A stub with one method passes today. If the service starts calling a second method, the test fails with
is not a function, which can look like a bug in the service. PrefercreateSpyObj<T>orimplements Tso the compiler tracks the real shape. - Over-stubbing. If every dependency is a stub, the test only proves that the service calls its stubs. Stub the boundaries (storage, network, time). Leave plain helper classes real.
- Stubbing
HttpClientby hand. A spy that returnsof(...)skips URL, method, and header handling, and it cannot simulate errors realistically. The next chapters replace the HTTP backend instead, which keeps the realHttpClientcode path under test. - Wrong injection token. The
providevalue must be the same token the service injects. Providing a subclass or a different class leaves the real one in use, and the test passes or fails for confusing reasons. - Component-level providers. If a component lists the service in its own
providers, aTestBedmodule provider does not replace it. UseTestBed.overrideComponentfor that case.
Exercise
OrderService injects Clock, a class with a method now(): Date. You want a test where now() returns new Date('2026-01-01') and you also want to check that OrderService calls now() once. Which provider form and helper would you use, and why is useValue: { now: () => date } alone not enough?
Show answer
Create a spy object with jasmine.createSpyObj<Clock>('Clock', ['now']), set clock.now.and.returnValue(new Date('2026-01-01')), and register it with { provide: Clock, useValue: clock }. After running the service, assert expect(clock.now).toHaveBeenCalledTimes(1). A plain object literal returns the date but records nothing, so it cannot verify the call count.