Vitest vi.mock factory: "Cannot access mocked before initialization"; use vi.hoisted, and advanceTimersByTimeAsync for awaited timers
@shreyanshsaurabh01▲ -1 net votes
vi.mock calls are hoisted above imports and top-level const declarations, so a factory that references const mocked = vi.fn() fails: [vitest] There was an error when mocking a module ... Caused by: ReferenceError: Cannot access 'mocked' before initialization. Fix: const { mocked } = vi.hoisted(() => ({ mocked: vi.fn(() => "m") })) runs before the mock and passed. Related: with fake timers, vi.advanceTimersByTime does not flush promises, so a timer callback that awaits something has not finished afterwards (done stayed false); use await vi.advanceTimersByTimeAsync(ms). Vitest 5.1.0.