Sub topic 8
Replacing Dependencies with vi.mock
This chapter assumes you already know how to create mock functions with vi.fn, set their behavior with mockReturnValue and mockResolvedValue, and assert on them with toHaveBeenCalledWith. It also assumes you can test async code with await and .resolves/.rejects. Those topics come from earlier chapters.
Passing a mock in as an argument works when you control the function signature. Real code often imports its dependencies directly, as in import { fetchUser } from './api.js'. A test cannot pass a replacement for that import. vi.mock solves this problem. It tells Vitest's module loader to hand out a fake version of a module to every file that imports it during the test file's run.
How vi.mock Works
The basic pattern
Here is the canonical case. user.js depends on api.js, which makes a real network request.
// 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 } from 'vitest'
import { getUserName } from './user.js'
import { fetchUser } from './api.js'
vi.mock('./api.js', () => ({
fetchUser: vi.fn(),
}))
it('returns the user name from the API', async () => {
fetchUser.mockResolvedValue({ name: 'Ada' })
await expect(getUserName(1)).resolves.toBe('Ada')
expect(fetchUser).toHaveBeenCalledWith(1)
})The second argument is a factory, which is a function that returns the object to use in place of the module's exports. The test imports fetchUser too. Because the module is mocked, that import gives the test the same vi.fn() that user.js receives, so the test can program it and inspect its calls.
Hoisting
vi.mock appears below the imports, yet it takes effect before them. Vitest rewrites the test file so that every vi.mock call moves to the top, ahead of all imports. Without this step, user.js would already have loaded the real api.js by the time the mock was registered.
Hoisting has one large consequence. The factory runs before any of your top-level code, so it cannot use variables you declared in the file:
// Broken: ReferenceError, because the factory runs before this line
const fetchUserMock = vi.fn()
vi.mock('./api.js', () => ({ fetchUser: fetchUserMock }))Sharing a variable with vi.hoisted
If you want a named handle to the mock, create it inside vi.hoisted. Vitest hoists that call as well and places it before the vi.mock calls.
// user.hoisted.test.js
import { it, expect, vi } from 'vitest'
import { getUserName } from './user.js'
const { fetchUserMock } = vi.hoisted(() => ({
fetchUserMock: vi.fn(),
}))
vi.mock('./api.js', () => ({ fetchUser: fetchUserMock }))
it('uses the hoisted mock', async () => {
fetchUserMock.mockResolvedValue({ name: 'Grace' })
await expect(getUserName(7)).resolves.toBe('Grace')
expect(fetchUserMock).toHaveBeenCalledWith(7)
})Variants of vi.mock
Automocking without a factory
If you call vi.mock('./api.js') with no factory, Vitest automocks the module. It loads the real module to read its shape, then replaces every exported function with a vi.fn() that returns undefined. Primitive exports keep their values, and objects and classes are mocked deeply. If a __mocks__/api.js file exists next to the module (or in a root __mocks__ folder for packages), Vitest uses that file instead.
// user.automock.test.js
import { it, expect, vi } from 'vitest'
import { getUserName } from './user.js'
import { fetchUser } from './api.js'
vi.mock('./api.js')
it('works with an automocked module', async () => {
vi.mocked(fetchUser).mockResolvedValue({ name: 'Linus' })
await expect(getUserName(3)).resolves.toBe('Linus')
})At runtime, vi.mocked simply returns its argument. In TypeScript it changes the static type to the mock type, so mockResolvedValue passes type checking.
Partial mocks with importOriginal
Sometimes you want to replace one export and keep the rest real. The factory receives an importOriginal helper for that purpose:
// utils.js
export function slugify(title) {
return title.toLowerCase().trim().replace(/\s+/g, '-')
}
export function randomId() {
return Math.random().toString(36).slice(2)
}
// post.js
import { slugify, randomId } from './utils.js'
export function createPost(title) {
return { id: randomId(), slug: slugify(title) }
}
// post.test.js
import { it, expect, vi } from 'vitest'
import { createPost } from './post.js'
vi.mock('./utils.js', async (importOriginal) => {
const actual = await importOriginal()
return { ...actual, randomId: vi.fn(() => 'id-123') }
})
it('builds a post with a predictable id and a real slug', () => {
expect(createPost('Hello World')).toEqual({ id: 'id-123', slug: 'hello-world' })
})Default exports
A factory's return value stands for the module namespace, so a default export must sit under the default key:
// logger.js
export default {
info(message) {
console.log(message)
},
}
// report.js
import logger from './logger.js'
export function report(count) {
logger.info(`Processed ${count} items`)
}
// report.test.js
import { it, expect, vi } from 'vitest'
import { report } from './report.js'
import logger from './logger.js'
vi.mock('./logger.js', () => ({
default: { info: vi.fn() },
}))
it('logs the processed count', () => {
report(5)
expect(logger.info).toHaveBeenCalledWith('Processed 5 items')
})If you forget the default key, Vitest throws an error saying that no "default" export is defined on the mock.
Packages and built-ins
Bare specifiers work too. vi.mock('axios') and vi.mock('node:fs') replace a dependency from node_modules or a Node built-in, and the same factory and automock rules apply.
Gotchas and Failure Modes
Mock state leaks between tests
A module mock lives for the whole test file. Call history and implementations set in one test are still there in the next one. Clear them in a hook:
import { beforeEach, vi } from 'vitest'
beforeEach(() => {
vi.resetAllMocks() // clears calls and resets implementations
})Use vi.clearAllMocks() when you only want to clear call history and keep the implementations. You can also turn this on project-wide with the clearMocks or mockReset config options. vi.restoreAllMocks() targets spies made with vi.spyOn, and it does not undo vi.mock.
Calls inside the same module are not replaced
vi.mock swaps what importers receive. If utils.js defines randomId and also calls it from another function in the same file, that internal call goes straight to the local binding, and the mock never sees it. You have two fixes. You can move the dependency into its own module, or you can pass it in as a parameter.
Other common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ReferenceError` inside the factory | The factory uses a top-level variable that hoisting placed after it | Create the value with `vi.hoisted`, or build it inside the factory |
| Real module still runs | The path does not match the module that is actually imported | Resolve the path from the test file, and check for aliases or file extensions |
| `No "default" export is defined` | A default import meets a factory with no `default` key | Return `{ default: ... }` |
| `mockResolvedValue is not a function` | The factory returned a plain function, not `vi.fn()` | Wrap the export in `vi.fn()` |
| Mock leaks into the next test | Mock state persists for the whole file | `vi.resetAllMocks()` in `beforeEach` |
vi.doMock for per-test variations
vi.doMock is not hoisted. It only affects modules imported after the call, which means you must load them with a dynamic await import(...). Call vi.resetModules() first so the module is not served from cache. Reach for it only when different tests need truly different module shapes. Changing return values with mockResolvedValue is usually simpler.
Choosing a Technique
| Situation | Prefer |
|---|---|
| You control the function signature | Pass a `vi.fn()` in as an argument |
| You want to watch or stub one method on a real object | `vi.spyOn` |
| Code imports the dependency directly | `vi.mock` with a factory |
| You need most of the module real | `vi.mock` with `importOriginal` |
| Many tests mock the same module the same way | A `__mocks__` file plus automock |
Module mocking is powerful, but it couples tests to your import graph. If you rename or move a file, every vi.mock path that points at it breaks. Mock at boundaries such as the network, the file system, and the clock, and let your own pure logic run for real.
Exercise
A test file declares const sendMock = vi.fn() at the top and then calls vi.mock('./mailer.js', () => ({ send: sendMock })). Running it throws a ReferenceError. Why, and how do you fix it while keeping a named handle to the mock?
Show answer
Vitest hoists vi.mock above all other code, so the factory runs before sendMock is initialized. Create the mock with const { sendMock } = vi.hoisted(() => ({ sendMock: vi.fn() })), which is hoisted ahead of vi.mock, and reference it in the factory.
Exercise
pricing.js exports getTaxRate() and totalWithTax(amount), and totalWithTax calls getTaxRate internally. A test mocks getTaxRate with importOriginal, keeps totalWithTax real, and still sees the real tax rate. Explain the result and give one fix.
Show answer
vi.mock only changes what importers of pricing.js receive. Inside pricing.js, totalWithTax calls its local getTaxRate binding, which the mock never replaces. Fixes: move getTaxRate into its own module and mock that module, or make totalWithTax accept the rate (or a rate function) as a parameter.
Exercise
Write the vi.mock call that replaces a module ./config.js, whose only export is a default object { apiUrl: '...' }, with { apiUrl: 'http://test.local' }.
Show answer
vi.mock('./config.js', () => ({ default: { apiUrl: 'http://test.local' } })). The default export must sit under the default key of the object the factory returns.