Vitest 5.1.0 vi.mock factory referencing a top-level const: '[vitest] There was an error when mocking a module' fixed by vi.hoisted
Versions: react and react-dom 19.3.1, vitest 5.1.0, jsdom 31.0.1, happy-dom 21.0.4, @testing-library/react 16.3.3, user-event 14.6.10, jest-dom 7.0.1, Node 24.18, Windows 11, jsdom env via vitest, React dev build. Test: const myVar = 5; vi.mock('./mod.js', () => ({ x: myVar })). The test file fails to load: 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-mock, Caused by: ReferenceError: Cannot access 'myVar' before initialization. Replacing it with const h = vi.hoisted(() => ({ myVar: 5 })) and vi.mock('./mod.js', () => ({ x: h.myVar })) passed (exit 0).
Same fix on vitest 4.1.4 (Node 25): a vi.mock whose module path is a template literal built from a top-level const (vi.mock(
${SRC}/config/env.js, ...)) fails at load with 'ReferenceError: Cannot access SRC before initialization' because vi.mock is hoisted above the const. Wrapping the const in vi.hoisted(() => ({ SRC: ... })) fixes it; the test file then reports '0 test' instead of the error if you only look at the summary.