Vitest becomes much easier to trust when each test replaces only the dependency it needs and restores the environment afterward. This guide provides a reusable checklist for mocking modules, spying on functions, stubbing API responses, controlling timers, and replacing browser or environment globals without creating order-dependent tests.
Overview
Mocking changes what a test can observe. A mock can replace a module, a spy can record calls while usually preserving the original implementation, a stub can provide a controlled value, and a fake can simulate a larger system such as a clock or server. Choose the smallest substitute that proves the behavior under test.
Before writing a mock, identify the boundary you are testing. If a function should format data returned by an API, mock the API boundary and test the formatting logic. If the purpose is to verify the API client itself, prefer a request-level test or a controlled server response. Avoid mocking the function being tested; doing so can make a test pass without exercising meaningful code.
The examples below assume a Vitest setup with vi available from vitest. Exact module behavior can depend on the Vitest and Vite versions, module format, and test configuration, so verify examples against the versions used by your project.
Checklist by scenario
Choose the right test double
| Need | Use | Typical Vitest API |
|---|---|---|
| Replace every import from a dependency | Module mock | vi.mock |
| Observe or temporarily replace one object method | Spy | vi.spyOn |
| Provide a controlled global, environment value, or implementation | Stub | vi.stubGlobal, vi.stubEnv, or vi.fn |
| Control time or model a broader external system | Fake | vi.useFakeTimers or a dedicated test server |
Mock a module dependency
Use a module mock when the unit under test imports a dependency whose result should be deterministic. The mock should be declared at module scope so Vitest can apply it before the dependent module is evaluated.
import { describe, expect, it, vi } from 'vitest'
import { getUserLabel } from './getUserLabel'
import { fetchUser } from './userApi'
vi.mock('./userApi', () => ({
fetchUser: vi.fn(),
}))
describe('getUserLabel', () => {
it('formats the user returned by the API client', async () => {
vi.mocked(fetchUser).mockResolvedValue({ id: '7', name: 'Ada' })
await expect(getUserLabel('7')).resolves.toBe('Ada')
expect(fetchUser).toHaveBeenCalledWith('7')
})
})
Keep the factory returned by vi.mock aligned with the exports the production module actually provides. For a different implementation per test, change the mock function's behavior inside the test and reset it between tests. When a static mock is too broad, consider vi.doMock with a subsequent dynamic import, while checking the current Vitest documentation for the module-loading behavior in your setup.
Mock fetch and API responses
A lightweight fetch mock is useful for testing code that interprets response status, JSON data, or request options. Stub the global explicitly and return a response-shaped object containing only what the code reads.
import { afterEach, describe, expect, it, vi } from 'vitest'
import { loadProfile } from './profile'
afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
describe('loadProfile', () => {
it('returns parsed profile data', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ name: 'Ada' }),
})
vi.stubGlobal('fetch', fetchMock)
await expect(loadProfile('7')).resolves.toEqual({ name: 'Ada' })
expect(fetchMock).toHaveBeenCalledWith('/api/profiles/7')
})
it('handles a failed response', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 404 }))
await expect(loadProfile('missing')).rejects.toThrow()
})
})
Test both the success path and the failure contract your application promises. If the real code reads headers, text, or response status, include those properties in the fake rather than silently omitting them.
Spy on methods without replacing the whole module
Spies are appropriate when the real implementation should run but the test also needs to verify a call. They are especially useful for logging, analytics, storage, or a small collaborator that is safe to execute.
import { describe, expect, it, vi } from 'vitest'
import * as analytics from './analytics'
import { saveSettings } from './settings'
it('records a settings update', async () => {
const track = vi.spyOn(analytics, 'track')
await saveSettings({ theme: 'dark' })
expect(track).toHaveBeenCalledWith('settings_updated', { theme: 'dark' })
track.mockRestore()
})
Use mockImplementation or mockResolvedValue on the spy when the real side effect is undesirable. Restore the individual spy or use a shared cleanup policy.
Control timers and dates
Fake timers make polling, debouncing, retries, and scheduled work deterministic. Enable them for the smallest scope possible, advance time deliberately, and return to real timers in cleanup.
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { scheduleRefresh } from './refresh'
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('refreshes after the configured delay', async () => {
const refresh = vi.fn()
scheduleRefresh(refresh, 1000)
expect(refresh).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(1000)
expect(refresh).toHaveBeenCalledOnce()
})
If code depends on the current date, set a known time with the fake-timer APIs and assert against that fixed value. Be careful with promises scheduled by timer callbacks; an asynchronous timer advancement method can ensure queued work has completed before the assertion.
Stub browser globals and environment values
Use vi.stubGlobal for browser objects such as matchMedia, IntersectionObserver, or a missing browser API. Use vi.stubEnv for values read at runtime. Environment variables captured during module evaluation may require module isolation or a fresh import.
import { afterEach, describe, expect, it, vi } from 'vitest'
import { isCompactLayout } from './layout'
afterEach(() => {
vi.unstubAllGlobals()
vi.unstubAllEnvs()
})
it('detects a compact viewport', () => {
vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: true }))
expect(isCompactLayout()).toBe(true)
})
it('uses the configured service URL', () => {
vi.stubEnv('SERVICE_URL', 'https://test.invalid')
// Call code that reads the environment at runtime here.
})
What to double-check
- Mock timing: Confirm whether the dependency is imported before the mock is registered. Static imports and hoisted mock declarations can behave differently from dynamic imports.
- Export shape: Match named, default, and nested exports exactly. A mock with the wrong shape can fail during import rather than during the assertion.
- Async completion: Await promises, use asynchronous timer advancement where needed, and avoid assertions that run before callbacks finish.
- Cleanup scope: Decide whether each test owns cleanup or the file has shared
afterEachhooks. Do not rely on test order. - Reset semantics:
clearAllMocksclears call history, while reset and restore operations affect implementations differently. Choose the operation that matches what the next test must receive. - Realistic contracts: A fake response should preserve the status, methods, and failure behavior that production code uses.
- Configuration: Check aliases, setup files, test environment selection, and whether browser APIs are supplied by the selected environment or must be stubbed.
Common mistakes
Mocking everything: Excessive mocks can make tests describe an imagined implementation rather than user-visible behavior. Keep integration coverage for important boundaries and use unit mocks for focused logic.
Leaking a fake: A stubbed global, fake timer, or modified environment value can affect later tests. Add cleanup immediately when introducing the substitute, then verify that the test passes alone and in the full suite.
Confusing call assertions with behavior assertions: Checking that a function was called does not prove the resulting UI, state transition, or error handling is correct. Assert the observable outcome as well as critical interaction details.
Using implementation-specific mocks: If a test must be rewritten whenever a private helper is renamed, the mock may be too close to the implementation. Prefer stable public boundaries.
Forgetting module cache effects: Configuration read at import time can persist across tests. If a test changes an imported value, isolate the module or restructure the code so configuration is injected explicitly.
When to revisit
Revisit this checklist when upgrading Vitest, Vite, the test environment, or the JavaScript module configuration. Review examples after a major release because mocking, hoisting, browser-environment, and fake-timer behavior can depend on the versions in use.
Also review the suite when CI reports order-dependent failures, when a feature adds a new API or timer boundary, or when a test requires several layers of custom setup. Run the affected test alone, then repeat it with the complete suite. Search for missing cleanup, shared mutable mocks, and environment values captured during import.
Before merging a new mock, use this short action list:
- Name the boundary being replaced and explain why it is needed.
- Select a mock, spy, stub, or fake that is no broader than necessary.
- Define success and failure behavior explicitly.
- Await asynchronous work and advance fake time deliberately.
- Restore mocks, globals, environments, and timers in cleanup.
- Run the test alone and with the full suite.
- Keep at least one higher-level test for important integration behavior.