Sub topic 12
Testing Timing Code with Fake Timers
This chapter assumes you can write basic Jest tests with test, expect, and jest.fn(). It also assumes you have the trailing-edge debounce and the timestamp-based throttle from earlier chapters.
Why Real Time Makes Bad Tests
A debounced function does nothing until time passes. You could test it by waiting with a real setTimeout inside the test, but that approach causes three problems:
- Slow suites. Every test waits for its full delay, and the delays add up across hundreds of tests.
- Flaky results. A busy CI machine can run a timer late, so a test that passes on your laptop fails on the build server.
- Edge cases you can't hit. It is hard to check what happens at exactly 99 ms versus 100 ms when you depend on the real clock.
Fake timers fix all three. Jest replaces setTimeout, clearTimeout, setInterval, and Date with versions it controls. Time then moves only when your test tells it to, and it moves instantly.
Testing Debounce
The test below includes the debounce implementation, so the file runs on its own.
function debounce(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
}
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
test('debounced function runs once after the wait', () => {
const fn = jest.fn();
const debounced = debounce(fn, 100);
debounced('a');
debounced('b');
debounced('c');
expect(fn).not.toHaveBeenCalled();
jest.advanceTimersByTime(99);
expect(fn).not.toHaveBeenCalled();
jest.advanceTimersByTime(1);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith('c');
});The two-step advance checks the boundary. At 99 ms the function has not run, and at 100 ms it has run exactly once, with the latest argument.
Testing Throttle
The timestamp throttle reads Date.now() and never calls setTimeout. Since Jest 27, the default ("modern") fake timers also mock Date, so advanceTimersByTime moves Date.now() forward too.
function throttle(fn, wait) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
}
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
test('throttled function runs at most once per window', () => {
const fn = jest.fn();
const throttled = throttle(fn, 200);
throttled(1); // runs immediately
throttled(2); // dropped
jest.advanceTimersByTime(199);
throttled(3); // dropped: only 199 ms passed
jest.advanceTimersByTime(1);
throttled(4); // runs: 200 ms passed
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenNthCalledWith(1, 1);
expect(fn).toHaveBeenNthCalledWith(2, 4);
});Useful Clock Controls
| Method | What it does | Use it when |
|---|---|---|
| `jest.advanceTimersByTime(ms)` | Moves the clock forward and fires every timer that comes due | You want to check behavior at exact boundaries |
| `jest.runOnlyPendingTimers()` | Fires the timers that are queued right now | A timer schedules another timer and you want one step |
| `jest.runAllTimers()` | Fires timers until none remain | You only care about the final result |
| `jest.setSystemTime(t)` | Sets `Date.now()` without firing timers | You are testing timestamp logic in isolation |
Common Errors
- Forgetting to restore real timers. Fake timers left on can break later tests that use promises or libraries that rely on the real clock. Restore them in
afterEach. - Creating the debounced function before enabling fake timers. This is safe for the debounce above, but code that captures
Date.now()when the wrapper is created will read the real clock. Turn fake timers on first. - Mixing fake timers with
await. Advancing timers does not flush promise callbacks. For async handlers, useawait jest.advanceTimersByTimeAsync(ms)(Jest 29.5+). - Using Vitest? The API has the same shape under
vi:vi.useFakeTimers()andvi.advanceTimersByTime(ms).
Exercise
You call a 100 ms debounced function at t=0 and again at t=60, then advance the fake clock to t=150. How many times has the wrapped function run, and what single advance would make it run?
Show answer
Zero times. The call at t=60 reset the timer, so it fires at t=160. One more jest.advanceTimersByTime(10) makes it run once, with the arguments from the t=60 call.
Exercise
A test of the timestamp throttle passes with modern fake timers but fails when the project sets legacy fake timers. Why?
Show answer
Legacy fake timers do not mock Date, so advanceTimersByTime does not move Date.now(). The throttle sees almost no elapsed time and drops calls the test expects to run.