Mocking Services and Dependencies
Provide test doubles via DI.
Why Mock Dependencies
A component test should isolate the component. If it injects an HttpClient-backed service, you do not want real network calls. Instead you provide a test double: a fake object that returns controlled data so tests are fast and deterministic.
Providing a Fake via useValue
The simplest double is a plain object supplied with useValue. Provide it under the same injection token the component asks for.
const fakeApi = { getUser: () => of({ name: 'Ada' }) };
TestBed.configureTestingModule({
imports: [ProfileComponent],
providers: [{ provide: UserApi, useValue: fakeApi }],
});All lessons in this course
- TestBed and Component Fixtures
- Testing Inputs, Outputs, and DOM
- Mocking Services and Dependencies
- Testing Signals and Async Code