vi.hoisted & vi.mocked in Vitest
From the Vitest cheat sheet · Module Mocking · verified Nov 2026
vi.hoisted & vi.mocked
Share mock functions with hoisted factories and get typed access to mocked imports
typescript
const mocks = vi.hoisted(() => ({ fetchUser: vi.fn() }))
vi.mock('./api', () => ({ fetchUser: mocks.fetchUser }))
test('configure per test', async () => {
mocks.fetchUser.mockResolvedValue({ id: 1 })
})📌 vi.hoisted runs before imports, so it can't use imported values
💡 vi.mocked() only changes types; it returns the same function
⚠️ v5 also requires vi.hoisted to be at the module top level
🟢 Set return values in beforeEach so each test starts fresh
vi.hoistedvi.mockedtypescript
Continue with Vitest
Save the full cheat sheet or work through every related task.