Sub topic 8
Replacing dependencies with mocks
This chapter assumes you can write a basic TestBed test, know how fixture.detectChanges() works, and understand Angular dependency injection with inject() and providers. It covers how to swap real services for test doubles. It uses vi.fn, vi.spyOn, and the providers array.
Why replace a dependency
A component test should check the component. If the component calls a service that makes HTTP requests, reads local storage, or starts timers, the test also depends on that code. It becomes slow and fragile, and a failure can come from the service instead of the component.
A test double is an object that stands in for a real dependency during a test. Three kinds appear in this chapter:
- A stub returns fixed data. It exists so the component has something to render.
- A mock records how it was called. You then assert on those calls.
- A spy wraps a real function and records calls, and it can still run the real code.
Vitest's vi.fn() creates a function that can act as either a stub or a mock. Most people call all of these "mocks", and this chapter does too.
The subject under test
The component below gets its data from UserService. The service uses HttpClient. The component turns the returned observable into a signal with toSignal.
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[],
});
}If you create UserListComponent without any setup, Angular tries to build UserService, which needs HttpClient. No HttpClient provider exists in the test, so creation fails with a NullInjectorError. You can fix this by providing a fake HttpClient, but it is simpler to replace UserService itself.
Replacing a service with a provider
Dependency injection looks up a token (here, the UserService class) and returns whatever the nearest provider supplies. In a test you register a different provider for the same token. This is the central technique of the chapter.
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);
});
});Read the test in order:
vi.fn(() => of([...]))makes a mock function. Its implementation returns a synchronous observable, which emits as soon as it is subscribed.{ provide: UserService, useValue: { list } }tells the injector: when someone asks forUserService, give them this plain object.configureTestingModuleruns beforecreateComponent. After the first component is created, the injector is fixed, so providers must be registered first.- The assertions check the rendered output and that the component called
listexactly once.
Because of(...) emits synchronously and toSignal subscribes in the component's field initializer, the signal already holds the data when the first detectChanges() renders the template.
Provider forms
useValue is one of several ways to supply a replacement. Choose the one that fits what you need.
| Form | Use it when |
|---|---|
| `{ provide: X, useValue: obj }` | A plain object is enough. This is the most common choice. |
| `{ provide: X, useClass: FakeX }` | The fake has its own logic or state, and Angular should construct it. |
| `{ provide: X, useFactory: () => ... }` | The fake is built from other values or needs setup code. |
| `{ provide: X, useExisting: Y }` | One token should resolve to an instance already provided under another token. |
A useValue object only needs the members the component touches. In the example, { list } has no other methods. If the component later calls a method the object lacks, the test fails with "is not a function", which tells you the component's needs have changed.
Keeping the fake type-safe
An object literal passed as useValue is not checked against the real class. If UserService.list is renamed, the test keeps compiling and fails at run time. You can get compile-time help with a Pick type:
import { vi } from 'vitest';
import { of } from 'rxjs';
import { UserService } from './user-list.component';
type UserServiceFake = Pick<UserService, 'list'>;
export function createUserServiceFake(users: string[]): UserServiceFake {
return { list: vi.fn(() => of(users)) as unknown as UserService['list'] };
}The Pick limits the fake to the methods you chose, and the key 'list' must exist on the real class. Renaming the method now breaks compilation in the test helper. The cast on vi.fn is needed because a mock's type differs from the method's type. Keep the cast in one helper instead of repeating it in each test.
Changing the return value per test
A shared fake often needs different data in different tests. Keep a reference to the mock and set its behavior inside each test, before the component is created.
import { TestBed } from '@angular/core/testing';
import { of, Subject } from 'rxjs';
import { beforeEach, describe, it, expect, vi } from 'vitest';
import { UserListComponent, UserService } from './user-list.component';
describe('UserListComponent states', () => {
const list = vi.fn();
beforeEach(() => {
list.mockReset();
TestBed.configureTestingModule({
providers: [{ provide: UserService, useValue: { list } }],
});
});
it('renders no items for an empty list', () => {
list.mockReturnValue(of([]));
const fixture = TestBed.createComponent(UserListComponent);
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('li').length).toBe(0);
});
it('renders items after a delayed response', () => {
const response = new Subject<string[]>();
list.mockReturnValue(response);
const fixture = TestBed.createComponent(UserListComponent);
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('li').length).toBe(0);
response.next(['Ada']);
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('li').length).toBe(1);
});
});The second test uses a Subject, which lets the test decide when the response arrives. This is a clean way to test "before" and "after" states without timers.
mockReset() clears recorded calls and any configured return value. Without it, a return value set in one test leaks into the next. Vitest also offers mockClear(), which clears only the call history, and mockRestore(), which is for spies and puts the original implementation back. You can set mockReset: true or restoreMocks: true in the Vitest configuration to do this for every test, but explicit resets in beforeEach are easier to read.
Spying on real objects with vi.spyOn
vi.fn makes a new function. vi.spyOn(object, 'method') wraps a method on an existing object. By default the spy calls through to the real implementation, and you can override that with mockReturnValue or mockImplementation.
This suits cases where you want the real service but need to observe or control one method. Here the real UserService is injected, and only list is replaced:
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { of } from 'rxjs';
import { describe, it, expect, vi } from 'vitest';
import { UserListComponent, UserService } from './user-list.component';
describe('UserListComponent with a spy', () => {
it('uses the real service but a stubbed list method', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const service = TestBed.inject(UserService);
const spy = vi.spyOn(service, 'list').mockReturnValue(of(['Linus']));
const fixture = TestBed.createComponent(UserListComponent);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('li').textContent).toBe('Linus');
expect(spy).toHaveBeenCalledOnce();
});
});Note the order: TestBed.inject runs first to get the service instance, the spy is installed, and only then is the component created. The component's inject(UserService) returns the same instance because providedIn: 'root' services are singletons within one TestBed injector. Installing the spy after creating the component would be too late here, because the component calls list() in its field initializer.
Call vi.restoreAllMocks() in afterEach when you spy on objects that outlive a test, such as window, console, or Math. TestBed builds a fresh injector for every test, so service instances created by it do not need this.
Which to choose
When the dependency is HttpClient itself, the next chapter covers HttpTestingController, which is a purpose-built replacement for the network layer.
Common errors
NullInjectorError: No provider for X. The component needs a token that nobody provided. Add a provider for it, either a fake or the real one with its own dependencies.TypeError: x.method is not a function. The fake object lacks a method the component calls. Add it to the fake.- Mock keeps old data in the next test. The return value was set once and never reset. Call
mockReset()inbeforeEach. - Spy installed too late. If the component calls the method during construction, the spy must exist before
createComponent. - Asserting on implementation, not behavior. A test that only checks
listwas called, without checking what appears on screen, passes even if the template is broken. Assert on the DOM first and on calls second. - Mocking what you own and trust. A pure helper class with no side effects usually works fine as the real thing. Replacing it adds code that can drift from the original.
Exercise
A component calls inject(UserService).list() in a field initializer. In your test you write const fixture = TestBed.createComponent(UserListComponent); vi.spyOn(TestBed.inject(UserService), 'list').mockReturnValue(of(['Ada']));. The test fails because the real list ran. What is wrong, and how do you fix it?
Show answer
The spy is installed after the component is created, but the component calls list() while it is being constructed, so the real method has already run. Move the TestBed.inject(UserService) and vi.spyOn(...) lines before TestBed.createComponent. The component then receives the same service instance with the spy already in place.
Exercise
You write TestBed.configureTestingModule({ providers: [{ provide: UserService, useValue: { list } }] }) with const list = vi.fn() declared once at the top of the file, and set list.mockReturnValue(of(['Ada'])) in the first test. The second test expects an empty list but sees 'Ada'. Why, and what is the smallest change that fixes it?
Show answer
The mock is shared across tests and keeps its configured return value, because nothing resets it. Add list.mockReset() in a beforeEach (or set the return value explicitly in every test). mockReset() clears both the call history and the configured return value, so each test starts clean.