Sub topic 8
Replacing Dependencies with vi.mock
This chapter assumes you already know how vi.fn works and how to test async code with await and .resolves. It covers vi.mock, which replaces a whole module for every file that imports it during a test run. You need this when the code under test imports its dependencies directly, so you cannot pass a mock in as an argument.
How vi.mock works
When you call vi.mock('./api.js', factory), Vitest records that any import of ./api.js should receive the object your factory returns instead of the real module. Vitest hoists the call, which means it moves the call above every import statement in the test file. This hoisting is why the mock is already in place when user.js loads and imports api.js.
A full example
// api.js
export async function fetchUser(id) {
const response = await fetch(`https://example.com/users/${id}`)
return response.json()
}
// user.js
import { fetchUser } from './api.js'
export async function getUserName(id) {
const user = await fetchUser(id)
return user.name
}
// user.test.js
import { it, expect, vi, beforeEach } from 'vitest'
import { getUserName } from './user.js'
import { fetchUser } from './api.js'
vi.mock('./api.js', () => ({
fetchUser: vi.fn(),
}))
beforeEach(() => {
vi.clearAllMocks()
})
it('returns the user name from the API', async () => {
fetchUser.mockResolvedValue({ name: 'Ada' })
await expect(getUserName(1)).resolves.toBe('Ada')
expect(fetchUser).toHaveBeenCalledWith(1)
})
it('propagates API errors', async () => {
fetchUser.mockRejectedValue(new Error('Network down'))
await expect(getUserName(1)).rejects.toThrow('Network down')
})The test file imports fetchUser from ./api.js too, and it gets the same mock that user.js uses. That shared reference is what lets the test set return values and check calls. In TypeScript, wrap it as vi.mocked(fetchUser) to get the mock's types.
Partial mocks with importOriginal
Sometimes you want to replace one export and keep the rest real. The factory receives an importOriginal helper for this:
vi.mock('./api.js', async (importOriginal) => {
const actual = await importOriginal()
return { ...actual, fetchUser: vi.fn() }
})If you call vi.mock('./api.js') with no factory, Vitest automocks the module. Every exported function becomes a vi.fn() that returns undefined.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ReferenceError` or `undefined` inside the factory | Hoisting moves the factory above your top-level variables | Define the values inside the factory, or create them with `vi.hoisted(() => ...)` |
| The real module still runs | The path does not resolve to the same file that the code under test imports | Write the path relative to the test file, or use the same package name the source code uses |
| A call count is too high in a later test | Mock state carries over between tests | Call `vi.clearAllMocks()` in `beforeEach`, or set `clearMocks: true` in the config |
| Mocking has no effect when placed inside a test | `vi.mock` applies only at module level | Use `vi.doMock` followed by a dynamic `import()` for per-test mocks |
Exercise
A test file declares const fakeUser = { name: 'Ada' } at the top, then calls vi.mock('./api.js', () => ({ fetchUser: vi.fn().mockResolvedValue(fakeUser) })). The test fails because the factory cannot access fakeUser. Why, and how do you fix it?
Show answer
Vitest hoists vi.mock above every other statement in the file, so the factory runs before fakeUser is defined. Create the value with const { fakeUser } = vi.hoisted(() => ({ fakeUser: { name: 'Ada' } })), which is hoisted as well. Another fix is to leave the factory as fetchUser: vi.fn() and call fetchUser.mockResolvedValue({ name: 'Ada' }) inside the test.
Exercise
You want to mock only fetchUser from ./api.js and keep its other export, buildUrl, real. Write the vi.mock call.
Show answer
vi.mock('./api.js', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, fetchUser: vi.fn() } })