Vitest cannot load a test file because a vi.mock factory throws
Your error
[vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock1 more line it can showFix it fast
Most common cause, 1 of 3The factory reads a mock function declared at the top of the test file
Build the shared mocks inside vi.hoisted.
import { expect, test, vi } from 'vitest'
import { getUser } from './api.js'
const mocks = vi.hoisted(() => ({
getUser: vi.fn(),
}))
vi.mock('./api.js', () => ({
getUser: mocks.getUser,
}))
test('returns the stored user', async () => {
mocks.getUser.mockResolvedValue({ id: 1 })
expect(await getUser()).toEqual({ id: 1 })
})Short answer
[vitest] There was an error when mocking a module wraps whatever a vi.mock factory threw. Vitest lifts vi.mock above all imports and code, so a factory that reads a top-level const, an imported name or a test's local variable runs before that value exists. Use vi.hoisted, import inside an async factory, or vi.doMock. Vitest 4 and 5.
Which cause do you have?
Run only the failing file and read the inner error. Vitest attaches the factory's own exception as the cause of the wrapper, and that inner message tells the cases apart: a name declared in the test file means cause 1, a __vi_import_ name means cause 2, and a variable that lives inside a test or hook means cause 3.
npx vitest run src/user.test.tsThen find the line you see in this list and open its fix:
- 1The factory reads a mock function declared at the top of the test file
The inner error says a const from your own test file, such as getUserMock, cannot be accessed before initialization - 2The factory uses a value from a static import, such as a fixture
The inner error names __vi_import_0__ or another __vi_import_ number instead of one of your own variable names - 3vi.mock sits inside a test or beforeEach and reads its local values
Vitest 4 also warns that the vi.mock call is not at the top level of the module; Vitest 5 refuses the file, saying the call was defined outside of the module's top level scope
What does the error look like?
[vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mockCannot access '__vi_import_0__' before initialization
Cause 1 of 3
The factory reads a mock function declared at the top of the test file
You seeThe inner error says a const from your own test file, such as getUserMock, cannot be accessed before initialization
Check
The vi.mock factory failed because it touched a variable that was not set yet. Vitest moves vi.mock to the start of the file, so a const written above it in the source still has no value when the factory runs. The mocker catches the exception and rethrows it with the generic hoisting message.
grep -n "vi.mock\|^const \|^let " src/user.test.tsFix
Build the shared mocks inside vi.hoisted. Its callback is lifted too, before vi.mock, and the object it returns can be read from the factory and changed per test.
import { expect, test, vi } from 'vitest'
import { getUser } from './api.js'
const mocks = vi.hoisted(() => ({
getUser: vi.fn(),
}))
vi.mock('./api.js', () => ({
getUser: mocks.getUser,
}))
test('returns the stored user', async () => {
mocks.getUser.mockResolvedValue({ id: 1 })
expect(await getUser()).toEqual({ id: 1 })
})Verify
The file loads and its tests report pass or fail on their own assertions instead of the mocking error.
npx vitest run src/user.test.tsConfirmed by vitest.dev
Cause 2 of 3
The factory uses a value from a static import, such as a fixture
You seeThe inner error names __vi_import_0__ or another __vi_import_ number instead of one of your own variable names
Check
When a file contains vi.mock, Vitest rewrites each static import into a dynamic one placed after the hoisted calls, and gives it a generated name of the form __vi_import_N__. If the factory runs while one of those bindings is still pending, reading the imported fixture throws a temporal dead zone error with that generated name.
grep -n "^import" src/user.test.tsFix
Make the factory async and import what it needs inside it. The factory may return a promise, and importOriginal gives you the real module when you want to keep part of it.
vi.mock('./api.js', async (importOriginal) => {
const original = await importOriginal()
const { sampleUser } = await import('./fixtures.js')
return {
...original,
getUser: vi.fn().mockResolvedValue(sampleUser),
}
})Verify
No __vi_import_ name appears in the output, and the test that uses the fixture runs.
npx vitest run src/user.test.tsConfirmed by vitest.dev
Cause 3 of 3
vi.mock sits inside a test or beforeEach and reads its local values
You seeVitest 4 also warns that the vi.mock call is not at the top level of the module; Vitest 5 refuses the file, saying the call was defined outside of the module's top level scope
Check
Writing vi.mock inside test() or beforeEach() does not delay it: the call is still lifted to the top and runs before anything else, so names from the surrounding block are out of reach. Vitest 5 turns this into its own error and asks you to move the call.
grep -n "vi.mock" src/user.test.tsFix
For a mock that differs per test, use vi.doMock, which stays where you write it, and import the module under test after it with a dynamic import. For one mock with changing return values, keep vi.mock at the top level and change the vi.hoisted functions inside each test.
import { beforeEach, expect, test, vi } from 'vitest'
beforeEach(() => {
vi.resetModules()
})
test('admin user', async () => {
const role = 'admin'
vi.doMock('./api.js', () => ({ getRole: () => role }))
const { canEdit } = await import('./permissions.js')
expect(canEdit()).toBe(true)
})Verify
Each test sees its own mocked value, and neither the warning nor the top level scope error is printed.
npx vitest run src/permissions.test.tsConfirmed by raw.githubusercontent.com
How do I stop it coming back?
- Keep every vi.mock and vi.hoisted call at the top level, directly under the imports, so the file reads in the order it runs.
- Give mock factories only vi.hoisted values, importOriginal and dynamic imports; nothing else from the file's outer scope.
- Import vi from vitest (or enable globals) in each test file, because Vitest only hoists calls on a vi it can see imported from the package.
- Upgrade to Vitest 5 to turn nested vi.mock calls into a load-time error instead of a confusing runtime one.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.