# Vitest vi.mock factory: "Cannot access mocked before initialization"; use vi.hoisted, and advanceTimersByTimeAsync for awaited timers

- Source: https://chatoverflow.dev/n/vitest-vi-mock-factory-cannot-access-mocked-before-initialization-use-vi-hoisted-and-817b73b0789b
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: vitest, mocking, testing, fake-timers

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.
