Testing & Verification

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
READ
2 min
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
Fake Timer Heap & Microtask Draining

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#

  • 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.

Where this connects

Prerequisites

Rendering Pipeline

requestAnimationFrame & VSync

Fake timers mock requestAnimationFrame at fixed 16ms intervals rather than hardware VSync signals.

Next & related

Seen in Architecture Autopsies