Testing & VerificationBaseline · Widely

Async Determinism, Fake Timers & Microtask Draining

Mental Model

Fake timers replace Date, setTimeout, and requestAnimationFrame with a virtual priority queue so time-dependent code runs in milliseconds without OS scheduler jitter. Advancing virtual time synchronously still fails when callbacks schedule Promises on the Microtask Queue unless you drain microtasks between ticks.

Interactive Simulator

Fake Timer Heap & Microtask Draining

Trace virtual clock advancement and microtask checkpoint draining across a debounced Promise.

Virtual Clock (0ms)
Timer Heap [200ms]
Microtask Queue (0)
Step 1 / 3: 1. Schedule Macrotask Timer

setTimeout inserts a callback at virtual timestamp 200ms without registering an OS timer.

setTimeout(() => fetchResults().then(setState), 200);
Internal State / Memory
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.

  1. Clock Virtualization: setTimeout(fn, 300) inserts { id, runAt: now + 300, fn } into the heap instead of registering an OS kernel timer.
  2. Synchronous vs Async Advancement: advanceTimersByTime(300) pops and executes macrotask callbacks synchronously, whereas advanceTimersByTimeAsync(300) yields an await Promise.resolve() checkpoint after each timer so microtasks drain in spec order.
  3. VSync Emulation: Mocked requestAnimationFrame schedules callbacks at fixed 16ms virtual offsets rather than waiting for compositor frame deadlines.
TS
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 synchronous tick() broke async/await chains by starving microtask checkpoints.
  • 2022 (advanceTimersByTimeAsync): Interleaved macrotask timer pops with microtask queue flushes, matching browser event-loop turn boundaries.

Production Pitfalls

Production Pitfall
  • Deadlocked waitFor Polling: Testing-library waitFor() polls with setTimeout internally; enabling fake timers without advanceTimers freezes waitFor() until the real test timeout kills the worker.
  • Unpatched queueMicrotask or Worker Clocks: Fake timers only patch globals in the main test realm; Web Workers and native C++ fetch timeouts keep reading real monotonic hardware clocks.
When Not to Use
  • When not to use Fake Timers: Never enable fake timers for tests awaiting real network sockets, IndexedDB transactions, or multi-frame CSS animations driven by compositor timelines, because virtualizing setTimeout stalls internal polling loops and desynchronizes real I/O deadlines.

Connections & Logical Next Steps

Seen in Architecture Autopsies