Mock a whole module with vi.mock
Replace an imported module in Vitest with vi.mock and a factory, which Vitest hoists above your imports so the code under test gets the fake.
When the code under test imports a module that talks to a network or a clock, vi.mock swaps it for a fake before anything else loads.
export function send(to, body) {
throw new Error('would send a real email');
}import { send } from './mailer.js';
export function signup(email) {
send(email, 'Welcome');
return `registered ${email}`;
}import { test, expect, vi } from 'vitest';
import { signup } from './signup.js';
import { send } from './mailer.js';
vi.mock('./mailer.js', () => ({
send: vi.fn(),
}));
test('sends a welcome mail', () => {
expect(signup('[email protected]')).toBe('registered [email protected]');
expect(send).toHaveBeenCalledWith('[email protected]', 'Welcome');
}); ✓ signup.test.js (1 test)
Test Files 1 passed (1)
Tests 1 passed (1)Vitest moves the vi.mock call to the top of the file when it transforms it, so it runs before the imports even though it is written below them. The factory returns the module's exports, and send becomes a spy. Calling vi.mock('./mailer.js') with no factory auto-mocks every export instead, turning functions into vi.fn() that return undefined. See vi.mock.
The factory runs lazily and cannot read variables declared in the test file, because of the hoisting. Use vi.hoisted for that. Mock at the boundary, such as the network, not your own pure functions.