Mocks and stubs are test doubles: stand-ins for real dependencies (network, database, time, third-party SDKs) that make tests fast, deterministic and isolated. A stub returns canned answers so the code under test can run ("the API returns this user"); you assert on the code's output. A mock is pre-programmed with expectations about how it's called, and the test verifies those interactions ("analytics.track was called once with 'purchase'"). A spy records calls on a real or fake function; a fake is a working lightweight implementation (in-memory DB). Use doubles at the boundaries, not for everything.
| Double | Purpose | Example |
|---|---|---|
| Dummy | Fills a parameter, never used | new Service(null) |
| Stub | Returns fixed data | getUser = () => Promise.resolve({ id: 1 }) |
| Spy | Records calls (may call through) | vi.spyOn(console, 'error') |
| Mock | Spy + expectations verified by the test | expect(track).toHaveBeenCalledWith('purchase', …) |
| Fake | Simplified working implementation | In-memory repository, MSW request handlers |
In Jest/Vitest, vi.fn()/jest.fn() creates a function that can act as stub, spy or mock depending on how you use it.
import { vi, test, expect } from 'vitest';
import { loadGreeting } from './greeting';
test('greets the user by name', async () => {
const api = { getUser: vi.fn().mockResolvedValue({ name: 'Ada' }) }; // stub
await expect(loadGreeting(api, 1)).resolves.toBe('Hello, Ada');
});
test('falls back when the user cannot be loaded', async () => {
const api = { getUser: vi.fn().mockRejectedValue(new Error('500')) };
await expect(loadGreeting(api, 1)).resolves.toBe('Hello, guest');
});
test('tracks a purchase once the order succeeds', async () => {
const analytics = { track: vi.fn() }; // mock
const orders = { create: vi.fn().mockResolvedValue({ id: 'o1', total: 42 }) };
await checkout({ orders, analytics }, cart);
expect(analytics.track).toHaveBeenCalledTimes(1);
expect(analytics.track).toHaveBeenCalledWith('purchase', { orderId: 'o1', value: 42 });
});
Interaction checks make sense when the side effect is the behaviour (sending an event, calling a callback prop, writing to storage).
vi.mock('./payments', () => ({ charge: vi.fn().mockResolvedValue({ ok: true }) }));
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
// … assert errorSpy calls …
errorSpy.mockRestore();
import { http, HttpResponse } from 'msw';
server.use(
http.get('/api/user/:id', ({ params }) => HttpResponse.json({ id: params.id, name: 'Ada' }))
);
Mocking at the network boundary lets the real fetch code, error handling and parsing run, so tests break only when actual behaviour changes. It's usually preferable to mocking your own apiClient module in component tests.
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
startCountdown();
vi.advanceTimersByTime(1000);
vi.useRealTimers();
vi.spyOn(Math, 'random').mockReturnValue(0.42);
mockReset/restoreAllMocks between tests causes order-dependent failures. Enable restoreMocks/clearMocks in config.vi.mock/jest.mock calls are hoisted above imports; variables they reference must be prefixed or defined with vi.hoisted.vi.fn() covers several roles.Spotted a mistake or a rights concern? Report an issue