vi.mock with a Factory in Vitest

From the Vitest cheat sheet ยท Module Mocking ยท verified Nov 2026

vi.mock with a Factory

Replace a module, or only some of its exports, with a factory

typescript
import { fetchUser } from './api'

vi.mock('./api', () => ({
  fetchUser: vi.fn().mockResolvedValue({ id: 1, name: 'Ada' }),
}))

test('uses the mock', async () => {
  expect(await fetchUser(1)).toEqual({ id: 1, name: 'Ada' })
})
๐Ÿ“Œ vi.mock is hoisted above imports and must sit at the top level
โš ๏ธ v5 throws if vi.mock is called inside describe, test or a function
๐Ÿ’ก vi.mock(import('./x'), ...) gives you a typed importOriginal
๐Ÿ” Return a default key for default exports, unlike Jest factories
vi.mockmodule-mockingimportOriginal

Continue with Vitest

Save the full cheat sheet or work through every related task.

More Vitest tasks

Back to the full Vitest cheat sheet