Community JavaScript Snippet

Freeze Time and Fast-Forward in Jest

The clock-control playbook I keep on a sticky note: freeze `Date.now`, advance pending timers without sleeping, and write tests for debounce/throttle helpers that actually finish in milliseconds.

Freeze Time and Fast-Forward in Jest

The clock-control playbook I keep on a sticky note: freeze `Date.now`, advance pending timers without sleeping, and write tests for debounce/throttle helpers that actually finish in milliseconds.

JavaScript
Frontend
3 snippets
testing
unit-testing
code-template
rohanbakr

By @rohanbakr

May 2, 2026

·

Updated May 20, 2026

193 views

2

4.6 (8)

The fundamental move is dependency injection: the unit under test receives a clock object instead of reaching for the global Date.now and setTimeout. In production you wire it to globalThis; in tests you wire it to a fake whose advance method walks the queue deterministically. This is exactly what jest.useFakeTimers() does under the hood, but writing a 30-line clock once teaches you why the flaky tests happen: any code that reads time without going through the injected clock will desync from the test. The test for our debounce now finishes in microseconds and never relies on setTimeout(0) tricks.