Skip to content
jshacks.dev
Testing

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.

1 min read
Summarize in AI

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.

mailer.jsJavaScript
export function send(to, body) {
  throw new Error('would send a real email');
}
signup.jsJavaScript
import { send } from './mailer.js';

export function signup(email) {
  send(email, 'Welcome');
  return `registered ${email}`;
}
signup.test.jsJavaScript
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');
});
Text
 ✓ 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.

Taggedvitest
Share

More snippets

Debugging

Debug a single Vitest test in VS Code

Run one Vitest file under the VS Code debugger with a launch configuration that passes the open file, so breakpoints in tests and source work. Vitest 3.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.