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.