Sub topic 8
Replacing dependencies with mocks
This chapter assumes you know TypeScript, Angular standalone components, dependency injection, and signals. You should also have written a basic TestBed test, as covered in the earlier chapters.
A component test should exercise the component, not its collaborators. If a component calls a service that makes HTTP requests, a failing network would break a test that has nothing to do with the network. A mock is a stand-in object that replaces a real dependency. You control what it returns, and you can check how the component used it.
The component under test
The example below has a service that fetches users and a component that renders them.
import { Component, inject, Injectable } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class UserService {
private readonly http = inject(HttpClient);
list() {
return this.http.get<string[]>('/api/users');
}
}
@Component({
selector: 'app-user-list',
template: `
<ul>
@for (name of names(); track name) {
<li>{{ name }}</li>
}
</ul>
`,
})
export class UserListComponent {
protected readonly names = toSignal(inject(UserService).list(), {
initialValue: [] as string[],
});
}Replacing a service with a provider
Angular resolves dependencies through providers. In a test you can register a different provider for the same token, so the component receives your object instead of the real service. The useValue form supplies a ready-made object.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { describe, it, expect, vi } from 'vitest';
import { UserListComponent, UserService } from './user-list.component';
describe('UserListComponent', () => {
it('renders the users returned by the service', () => {
const list = vi.fn(() => of(['Ada', 'Grace']));
TestBed.configureTestingModule({
providers: [{ provide: UserService, useValue: { list } }],
});
const fixture = TestBed.createComponent(UserListComponent);
fixture.detectChanges();
const items = Array.from<HTMLElement>(
fixture.nativeElement.querySelectorAll('li'),
).map((li) => li.textContent);
expect(items).toEqual(['Ada', 'Grace']);
expect(list).toHaveBeenCalledTimes(1);
});
});Three things happen here:
vi.fn()creates a mock function. It records every call and can have a fixed implementation, here one that returnsof([...]).{ provide: UserService, useValue: { list } }gives the component a plain object with only the members it uses.HttpClientis never needed, so no HTTP providers are required.of(...)emits synchronously. The signal created bytoSignalalready holds the data whendetectChanges()renders, so the test needs no waiting.
Choosing a replacement style
| Style | Use it when |
|---|---|
| `useValue` with an object of `vi.fn` members | The component uses only a few members of the service. |
| `useClass` with a hand-written fake class | Several tests share a fake with some real-looking behavior. |
| `vi.spyOn(realInstance, 'method')` | You want the real object but need to replace or observe one method. |
vi.spyOn wraps a method on an existing object. For example, after const service = TestBed.inject(UserService), calling vi.spyOn(service, 'list').mockReturnValue(of(['Ada'])) replaces only list. Use this form when the real service can be constructed without side effects. Call vi.restoreAllMocks() in afterEach if the spy could affect other tests.
Common errors
- Partial mocks. If the component calls a member your object lacks, you get
x is not a function. Add the member to the mock. - Mocks that drift. A plain object is not checked against the real class. Typing it, for example as
Pick<UserService, 'list'>, makes the compiler flag renamed methods. - Asserting too much. Checking
toHaveBeenCalledTimes(1)is useful for a fetch on startup. Checking every internal call ties the test to the implementation. - Shared state. A
vi.fncreated outside a test keeps its call history across tests. Create mocks inside each test or inbeforeEach.
Exercise
Why does the test use of(['Ada', 'Grace']) instead of an asynchronous source, and what would you need to change if the mock returned an observable that emits later?
Show answer
of emits synchronously, so toSignal holds the values before the first detectChanges() renders the template, and no waiting is needed. With a later emission, the test would have to trigger the emission (for example with a Subject and next) and then call fixture.detectChanges() again before querying the DOM.
Exercise
A test uses { provide: UserService, useValue: {} } and fails with list is not a function. What is the fix, and how can you stop this kind of mistake from compiling?
Show answer
Add a list member to the mock, such as { list: vi.fn(() => of([])) }. Typing the mock as Pick<UserService, 'list'> makes the compiler report a missing or renamed member.