Mocking, Stubs & Test Doubles
Context
Every test needs to control the world around the code under test. Production code talks to HTTP APIs, reads from the filesystem, checks the current time, and calls third-party SDKs — none of which are controllable, deterministic, or fast in a test environment. Test doubles are the solution: replacements for real dependencies that give your test full control over what the dependency returns and whether it was called.
Gerard Meszaros codified the vocabulary in xUnit Test Patterns (2007). The terms are still the reference point for the field, though they are used loosely in practice:
Mock — an object that records how it was called, and whose behavior is verified in the test assertion. The test explicitly asserts that the mock was called with specific arguments. In Vitest: a vi.fn() where you later write expect(sendEmail).toHaveBeenCalledWith('alice@example.com', 'Welcome').
Stub — an object that returns a fixed value when called, without being verified. The test does not assert that the stub was called; it only cares about how the code under test reacts to the return value. A stub that always returns { ok: true } from a network call is a stub, not a mock.
Spy — wraps the real implementation and records calls without replacing behavior. vi.spyOn(console, 'warn') lets the real console.warn run while recording that it was called. You can then assert on calls, or optionally replace the implementation.
Fake — a working simplified implementation of a dependency. An in-memory SQLite database used in tests instead of a real PostgreSQL server is a fake. It has real behavior (you can insert and query rows) but is not the production system.
Dummy — a placeholder passed to satisfy a function signature but never actually used during the test. A dummy email address passed to a function that requires a User object but only reads user.id is a dummy.
In day-to-day Vitest/Jest usage, "mock" is used colloquially for all five types. The distinctions matter when reasoning about what a test actually covers.
Design Thinking
Why MSW is the preferred API mocking approach
The naive approach to API mocking replaces fetch globally:
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({ users: [] }),
})This has two serious problems. First, it mocks the implementation (fetch) not the behavior (what the API returns). If your code uses axios, or a wrapper that calls fetch differently, the mock does not apply. If the code switches from fetch to axios, the test breaks for the wrong reason. Second, the mock bypasses the real response parsing path. Your code probably calls response.json() and maps the result through a schema validator — none of that runs when fetch is replaced.
MSW intercepts at the network layer, below all HTTP client libraries. The real fetch runs. The real response object is constructed. The real JSON parsing runs. The real schema validation runs. Only the network I/O is intercepted — the fake response is injected at the point where the browser (or Node.js) would have received bytes from the server.
This means the test exercises the same code path as production. A bug in your response parsing or schema mapping will be caught. The same MSW handler works in browser-based integration tests (using a Service Worker) and in Node.js unit tests (using msw/node) without any change to the handler code.
Why vi.mock() is powerful but dangerous
vi.mock('path/to/module') replaces an entire module with a factory-generated replacement before the test runs. It is powerful because it applies to every import of the module in the test file, including transitive imports. It is dangerous for the same reason: a test that mocks api/users does not execute any of the real code in api/users. If the real module has a bug — wrong endpoint URL, wrong field mapping, missing error handling — the test will still pass because the mock returns whatever value you tell it to return.
vi.mock() is appropriate when the module is a system boundary (an HTTP client, a filesystem wrapper, a third-party SDK) and you cannot or should not run the real thing. It is not appropriate for internal utility functions where calling the real thing is both possible and better.
The boundary rule
Draw a line around the code under test. On one side: code you own, logic you can run in a test environment, functions that are fast and deterministic. On the other side: the network, the filesystem, the system clock, third-party SDKs whose side effects you cannot control.
Mock everything on the boundary. Do not reach across the boundary to mock things on your own side.
When you find yourself mocking a function your own code defines — vi.mock('./utils/formatDate') to avoid dealing with date formatting — that is a smell. Either the function genuinely crosses a boundary (it reads from the system clock, in which case mock the clock, not the function), or it does not (in which case call the real function and write the test to handle real dates).
Why over-mocking is a test smell
A test suite where every function is mocked gives false confidence. The mocks return "correct" values because you wrote them to — not because the code works. A refactor that changes the return shape of an internal function will break the real code in production without breaking the tests, because the tests mock the old shape.
The rule of thumb: if removing the mock would require running something slow, nondeterministic, or with external side effects — keep the mock. If removing the mock would just mean calling the real function — remove it.
Best Practices
MOCK AT SYSTEM BOUNDARIES ONLY — HTTP, FILESYSTEM, SYSTEM TIME, AND EXTERNAL SDKS. The boundary rule is: mock everything on the far side of a line you draw around code you own; call the real thing on your side of that line. If a function is fast, deterministic, and free of external side effects, it MUST NOT be mocked — mocking it tests your mock, not your code. A mock is justified only when removing it would require invoking something slow, nondeterministic, or with real external side effects.
USE MSW FOR HTTP API MOCKING INSTEAD OF REPLACING global.fetch OR axios DIRECTLY. MSW intercepts at the network layer, below all HTTP client libraries, so the real fetch runs, the real response object is constructed, and the real JSON parsing and schema validation execute. Replacing global.fetch with vi.fn() MUST NOT be the default approach because it bypasses every layer of response handling your code runs in production, meaning a bug in response parsing will not be caught. The same MSW handler works in both Node.js test environments (msw/node) and browser-based integration tests without modification.
SET onUnhandledRequest: 'error' IN server.listen() SO UNEXPECTED REQUESTS CAUSE TEST FAILURES. The default MSW behavior on unhandled requests is a console warning, which is easy to miss. Configuring 'error' turns any request that matches no handler into a test failure, catching the case where your code makes an API call you did not intend to cover. This SHOULD be the standard configuration in every test setup file.
USE vi.setSystemTime() TO FREEZE THE CLOCK RATHER THAN MOCKING DATE UTILITY FUNCTIONS. Mocking a getTimestamp() helper function fixes only the one code path that calls it; third-party libraries and other internal modules reading Date.now() directly still see real time. vi.useFakeTimers() followed by vi.setSystemTime() freezes time at the source so every code path — including dependencies — MUST see the frozen value. Always restore real timers with vi.useRealTimers() in afterEach.
Visual
Mock Boundary Diagram
The test interacts with code it owns through real function calls. At the system boundary, real external dependencies are replaced by test doubles. The external system is never invoked.
Example
1. vi.fn() vs vi.spyOn() — the key difference
vi.fn() creates a standalone mock function with no real implementation. vi.spyOn() wraps an existing method, preserving the real implementation while recording calls.
// vi.fn() — creates a mock from scratch, no real implementation runs
import { vi, expect, it, describe, beforeEach } from 'vitest'
describe('notification service', () => {
it('calls sendEmail with the correct arguments', async () => {
// vi.fn() replaces the implementation entirely.
// Nothing from the real sendEmail function runs.
const sendEmail = vi.fn().mockResolvedValue({ delivered: true })
await notifyUser({ email: 'alice@example.com', name: 'Alice' }, sendEmail)
// This is a MOCK assertion — we verify HOW it was called, not just THAT it was called.
expect(sendEmail).toHaveBeenCalledOnce()
expect(sendEmail).toHaveBeenCalledWith(
'alice@example.com',
'Welcome, Alice',
expect.objectContaining({ from: 'noreply@example.com' }),
)
})
it('does not call sendEmail when user has unsubscribed', async () => {
const sendEmail = vi.fn()
await notifyUser({ email: 'bob@example.com', name: 'Bob', unsubscribed: true }, sendEmail)
// A stub-style assertion — we care that it was NOT called, not about arguments.
expect(sendEmail).not.toHaveBeenCalled()
})
})// vi.spyOn() — wraps the real implementation, records calls
import { vi, expect, it, describe, afterEach } from 'vitest'
import * as analytics from './analytics'
describe('product page', () => {
afterEach(() => {
// Restore the original implementation after each test.
vi.restoreAllMocks()
})
it('tracks a page view on mount', () => {
// The real analytics.track() runs — vi.spyOn does not replace it.
// We only record that it was called so we can assert on it.
const trackSpy = vi.spyOn(analytics, 'track')
mountProductPage({ productId: 'p-123' })
expect(trackSpy).toHaveBeenCalledWith('page_view', { productId: 'p-123' })
})
it('can optionally replace the implementation', () => {
// You can call .mockImplementation() on a spy to replace the real method.
const trackSpy = vi.spyOn(analytics, 'track').mockImplementation(() => {})
mountProductPage({ productId: 'p-456' })
expect(trackSpy).toHaveBeenCalledTimes(1)
// The real analytics.track did NOT run — we replaced it.
})
})2. vi.mock() for module-level replacement
vi.mock() is hoisted to the top of the file by Vitest's transform step — it runs before any imports, so the mocked version is what every import in the file receives. The factory function defines what the mock module exports.
// src/api/users.ts (the real module — we do NOT want this to run in tests
// because it makes real HTTP requests)
export async function getUsers(): Promise<User[]> {
const res = await fetch('/api/users')
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}
export async function createUser(data: CreateUserInput): Promise<User> {
const res = await fetch('/api/users', {
method: 'POST',
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json' },
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}// src/components/UserList.test.ts
import { vi, expect, it, describe, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import UserList from './UserList'
// vi.mock() is hoisted — this runs before any imports are resolved.
// Every import of '../api/users' in this test file (and in UserList itself)
// receives the mocked version.
vi.mock('../api/users', () => ({
getUsers: vi.fn(),
createUser: vi.fn(),
}))
// Import after vi.mock() so we get the mocked version.
import { getUsers } from '../api/users'
describe('UserList', () => {
beforeEach(() => {
// Reset call history and return values before each test.
vi.clearAllMocks()
})
it('renders a list of users returned by the API', async () => {
// Configure the stub return value for this test.
vi.mocked(getUsers).mockResolvedValue([
{ id: '1', name: 'Alice', email: 'alice@example.com' },
{ id: '2', name: 'Bob', email: 'bob@example.com' },
])
render(<UserList />)
await waitFor(() => {
expect(screen.getByText('Alice')).toBeInTheDocument()
expect(screen.getByText('Bob')).toBeInTheDocument()
})
})
it('shows an error state when the API call fails', async () => {
vi.mocked(getUsers).mockRejectedValue(new Error('HTTP 503'))
render(<UserList />)
await waitFor(() => {
expect(screen.getByRole('alert')).toHaveTextContent('Failed to load users')
})
})
})3. MSW: setupServer, handlers, per-test overrides
MSW handlers intercept requests at the network layer. The same handler format works in Node.js tests (msw/node) and browser integration tests (Service Worker).
// src/mocks/handlers.ts — shared handlers used across all tests
import { http, HttpResponse } from 'msw'
export const handlers = [
http.get('/api/users', () => {
return HttpResponse.json([
{ id: '1', name: 'Alice', email: 'alice@example.com' },
{ id: '2', name: 'Bob', email: 'bob@example.com' },
])
}),
http.post('/api/users', async ({ request }) => {
const body = await request.json() as { name: string; email: string }
return HttpResponse.json(
{ id: '3', name: body.name, email: body.email },
{ status: 201 },
)
}),
http.delete('/api/users/:id', ({ params }) => {
return new HttpResponse(null, { status: 204 })
}),
]// src/setupTests.ts — Vitest setup file (configured in vitest.config.ts setupFiles)
import { setupServer } from 'msw/node'
import { handlers } from './mocks/handlers'
// Create the server once and export it so tests can call server.use() for overrides.
export const server = setupServer(...handlers)
// Start the server before all tests, reset handlers after each test,
// and stop the server after all tests complete.
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())// src/components/UserList.test.ts — using MSW instead of vi.mock()
import { server } from '../setupTests'
import { http, HttpResponse } from 'msw'
import { render, screen, waitFor } from '@testing-library/react'
import UserList from './UserList'
it('renders users from the API', async () => {
// The default handler in handlers.ts returns Alice and Bob.
// No override needed — the test just renders and asserts.
render(<UserList />)
await waitFor(() => {
expect(screen.getByText('Alice')).toBeInTheDocument()
expect(screen.getByText('Bob')).toBeInTheDocument()
})
})
it('shows an error banner when the API returns 500', async () => {
// server.use() adds a one-time override for this test only.
// After this test, server.resetHandlers() (in afterEach) removes the override.
server.use(
http.get('/api/users', () => {
return new HttpResponse(null, { status: 500 })
}),
)
render(<UserList />)
await waitFor(() => {
expect(screen.getByRole('alert')).toHaveTextContent('Failed to load users')
})
})
it('shows a loading state while the request is in flight', async () => {
// Use a never-resolving response to keep the loading state visible.
server.use(
http.get('/api/users', () => new Promise(() => {})),
)
render(<UserList />)
expect(screen.getByRole('progressbar')).toBeInTheDocument()
})4. vi.setSystemTime() for date-dependent logic
import { vi, expect, it, describe, beforeEach, afterEach } from 'vitest'
import { isWeekend, formatRelativeDate, isExpired } from './date-utils'
describe('date-dependent utilities', () => {
beforeEach(() => {
// Freeze time to a known value: Wednesday, 2026-01-14 09:00 UTC.
// Date.now(), new Date(), and performance.now() all reflect this value.
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-01-14T09:00:00.000Z'))
})
afterEach(() => {
// Restore real timers after each test.
vi.useRealTimers()
})
it('isWeekend returns false on a Wednesday', () => {
expect(isWeekend()).toBe(false)
})
it('formatRelativeDate returns "3 days ago" for a date 3 days in the past', () => {
const threeDaysAgo = new Date('2026-01-11T09:00:00.000Z')
expect(formatRelativeDate(threeDaysAgo)).toBe('3 days ago')
})
it('isExpired returns true when the expiry date has passed', () => {
const yesterday = new Date('2026-01-13T09:00:00.000Z')
expect(isExpired(yesterday)).toBe(true)
})
it('isExpired returns false when the expiry date is in the future', () => {
const tomorrow = new Date('2026-01-15T09:00:00.000Z')
expect(isExpired(tomorrow)).toBe(false)
})
})Mock cleanup: clearAllMocks vs resetAllMocks vs restoreAllMocks
The three cleanup functions do different things. Mixing them up causes tests to bleed state into each other.
// In vitest.config.ts — configure globally to avoid per-file boilerplate
export default defineConfig({
test: {
// clearMocks: true — clears call history and instances after each test
// does NOT reset mock return values
// resetMocks: true — clears call history AND resets return values to undefined
// does NOT restore vi.spyOn() to the original implementation
// restoreMocks: true — clears call history, resets return values, AND restores
// vi.spyOn() to the original implementation
//
// For most projects, restoreMocks: true is the safest default.
restoreMocks: true,
},
})// What each function does in isolation:
const fn = vi.fn().mockReturnValue(42)
fn()
fn()
vi.clearAllMocks()
// fn.mock.calls is now [] — call history cleared
// fn() still returns 42 — return value NOT reset
// vi.spyOn stubs NOT restored
vi.resetAllMocks()
// fn.mock.calls is now [] — call history cleared
// fn() now returns undefined — return value reset
// vi.spyOn stubs NOT restored
vi.restoreAllMocks()
// fn.mock.calls is now [] — call history cleared
// fn() now returns undefined — return value reset
// vi.spyOn stubs restored to original implementationCommon Mistakes
Forgetting that vi.mock() is hoisted. vi.mock() is moved to the top of the file at compile time by Vitest's transform step, before any import statements execute. Writing code between import statements and vi.mock() calls and expecting it to run first will produce confusing results. All vi.mock() calls run first, always.
Not resetting mocks between tests. A vi.fn().mockResolvedValue(users) set in one test bleeds into the next if vi.clearAllMocks() or restoreMocks: true is not configured. The second test passes because of the first test's mock state, not because of its own setup. Configure restoreMocks: true in vitest.config.ts to reset all mocks automatically after each test.
Related FEEs
- FEE-1100 Testing Strategies Overview — testing pyramid and the cost-confidence trade-off that determines where mocking is worthwhile
- FEE-1101 Unit Testing with Vitest —
vi.fn()fundamentals and test structure in Vitest - FEE-1102 Component Testing — mocking in component tests: MSW with Testing Library, mocking child components
- FEE-1103 End-to-End Testing: Playwright & Cypress —
cy.intercept()and Playwrightroutefor network mocking in E2E tests
References
- MSW — Getting Started — installation, handler syntax, browser and Node.js integration
- MSW — Comparison with other approaches — why MSW intercepts at the network level and what that means for test fidelity
- Vitest — Mocking —
vi.fn(),vi.spyOn(),vi.mock(),vi.stubGlobal(),vi.setSystemTime(), and mock cleanup - Gerard Meszaros — Test Double taxonomy (martinfowler.com) — Martin Fowler's summary of Meszaros's five test double types with definitions and examples
- Martin Fowler — Mocks Aren't Stubs — the distinction between state verification (stubs) and behavior verification (mocks), and why it matters
- Vitest —
vi.mock()hoisting behavior — whyvi.mock()calls are moved to the top of the file and how factory functions work