vi.mock factory throws cannot access mockDb before initialization Mocking
const mockDb = { query: vi.fn() }
vi.mock('~/db', () => ({ db: mockDb }))
Every test in the file dies with ReferenceError: Cannot access 'mockDb' before initialization.
The part I cannot get my head around: the const already is above the mock. Moving it further up changes nothing. Vitest 3, TS, ~ alias resolved through the vite tsconfig paths plugin.
@kombucha_kai · 2mo ago · 2 replies
vi.mockcalls are hoisted to the top of the module by the transform, above everything you wrote, regardless of where they appear in the file. That is deliberate - the mock has to be registered before the imports it replaces are evaluated. So the factory runs first andmockDbis still in its temporal dead zone.Hoist the value with the mock:
vi.hoistedgets lifted alongside the mock, so both the factory and your tests can see the same object. Rule of thumb: anything the factory touches must be created insidevi.hoisted.Reply
Report
@thriftedtweed · 2mo ago
And for resetting between tests, call
mockDb.query.mockReset()yourself inbeforeEach. TheclearMocksconfig option clears call history but leaves implementations in place, which produces a very confusing second test.Reply
Report