Async Determinism, Fake Timers & Microtask Draining
Real setTimeout calls in tests bake CI CPU jitter into assertions; fake timers replace wall-clock APIs with a deterministic queue that still breaks if microtasks are not drained.
About this page
Fake Timer Heap & Microtask Draining
Trace virtual clock advancement and microtask checkpoint draining across a debounced Promise.
setTimeout inserts a callback at virtual timestamp 200ms without registering an OS timer.
setTimeout(() => fetchResults().then(setState), 200);- virtualNowMs
- 0
- timerHeapSize
- 1
- microtaskQueueSize
- 0
Under the Hood#
Calling useFakeTimers() monkey-patches global scheduling APIs on globalThis and maintains an integer now cursor plus a min-heap of pending timer records.
- Clock Virtualization:
setTimeout(fn, 300)inserts{ id, runAt: now + 300, fn }into the heap instead of registering an OS kernel timer. - Synchronous vs Async Advancement:
advanceTimersByTime(300)pops and executes macrotask callbacks synchronously, whereasadvanceTimersByTimeAsync(300)yields anawait Promise.resolve()checkpoint after each timer so microtasks drain in spec order. - VSync Emulation: Mocked requestAnimationFrame schedules callbacks at fixed 16ms virtual offsets rather than waiting for compositor frame deadlines.
vi.useFakeTimers();
let saved = false;
setTimeout(() => Promise.resolve().then(() => { saved = true; }), 200);
// Sync advance runs setTimeout, but Promise.then stays queued until await
await vi.advanceTimersByTimeAsync(200);
expect(saved).toBe(true);Problem Genealogy#
- 2012 (Real
sleep(500)in Mocha/Jasmine): Suites accumulated 30s-120s of idle wall-clock wait time and flaked whenever CI runners throttled CPU shares. - 2015 (
lolex/@sinonjs/fake-timers): Eliminated wall-clock waits, but synchronoustick()brokeasync/awaitchains by starving microtask checkpoints. - 2022 (
advanceTimersByTimeAsync): Interleaved macrotask timer pops with microtask queue flushes, matching browser event-loop turn boundaries.
Production Pitfalls#
- Deadlocked
waitForPolling: Testing-librarywaitFor()polls withsetTimeoutinternally; enabling fake timers withoutadvanceTimersfreezeswaitFor()until the real test timeout kills the worker. - Unpatched
queueMicrotaskor Worker Clocks: Fake timers only patch globals in the main test realm; Web Workers and native C++fetchtimeouts keep reading real monotonic hardware clocks.
Where this connects
Prerequisites
Event Loop, Macrotasks, and Microtask Queue
Advancing fake macrotask timers without draining the microtask queue leaves Promise continuations unresolved.
requestAnimationFrame & VSync
Fake timers mock requestAnimationFrame at fixed 16ms intervals rather than hardware VSync signals.
Next & related
Test Fidelity Spectrum: Unit, Component, Browser & E2E
Lower-fidelity unit and component layers rely on deterministic fake timers rather than wall-clock waits.
Seen in Architecture Autopsies
Autopsy #07: 412 Green Tests and a Dead Menu Button
vi.useFakeTimers() advances animation delays synchronously, masking a 300ms transition race that hides the menu.