Sub topic 12
Testing Timing Code with Fake Timers
A debounce or throttle bug is about time: a call fires too early, too late, twice, or not at all. If you test those functions with real timers, the test has to actually wait. A 300 ms debounce costs 300 ms per test, and a loaded CI machine can make the timing flaky. Fake timers solve this. They replace setTimeout, clearTimeout, Date, and related APIs with a virtual clock that moves only when your test moves it.
This chapter assumes you can write and run basic Jest tests with test, expect, and jest.fn(). It also assumes you have read the earlier chapters that build debounce, debounceLeading, throttle, rafThrottle, and the cancel/flush controls. The examples use Jest 29 or later. A table near the end maps the same calls to Vitest.
How a Fake Clock Works
When you call jest.useFakeTimers(), Jest swaps the global timer functions for versions from @sinonjs/fake-timers. A scheduled callback does not go to the event loop. It goes into a queue inside the fake clock, tagged with the virtual time when it should run. Nothing runs until you call a function such as jest.advanceTimersByTime(ms). That function moves the virtual clock forward and runs, in order, every callback whose due time has been reached. These callbacks run synchronously inside the advanceTimersByTime call, so your assertions on the next line already see their effects.
The fake clock also replaces Date. As virtual time advances, Date.now() advances with it. The timestamp-based throttle depends on this.
The Code Under Test
Put the implementations from earlier chapters in one module so the tests can import them. The debounce here is the version with cancel and flush, and throttle is the version with a trailing call.
// timing.js
function debounce(fn, wait) {
let timerId;
let lastThis;
let lastArgs;
function invoke() {
const ctx = lastThis;
const args = lastArgs;
timerId = undefined;
lastThis = undefined;
lastArgs = undefined;
return fn.apply(ctx, args);
}
function debounced(...args) {
lastThis = this;
lastArgs = args;
clearTimeout(timerId);
timerId = setTimeout(invoke, wait);
}
debounced.cancel = function () {
clearTimeout(timerId);
timerId = undefined;
lastThis = undefined;
lastArgs = undefined;
};
debounced.flush = function () {
if (timerId !== undefined) {
clearTimeout(timerId);
return invoke();
}
};
return debounced;
}
function debounceLeading(fn, wait) {
let timerId;
return function (...args) {
if (timerId === undefined) {
fn.apply(this, args);
}
clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = undefined;
}, wait);
};
}
function throttle(fn, wait) {
let last = 0;
let timerId;
let pendingThis;
let pendingArgs;
return function (...args) {
const now = Date.now();
const remaining = wait - (now - last);
if (remaining <= 0) {
clearTimeout(timerId);
timerId = undefined;
last = now;
fn.apply(this, args);
} else {
pendingThis = this;
pendingArgs = args;
if (timerId === undefined) {
timerId = setTimeout(() => {
last = Date.now();
timerId = undefined;
fn.apply(pendingThis, pendingArgs);
}, remaining);
}
}
};
}
function rafThrottle(fn) {
let frameId = null;
let lastArgs;
return function (...args) {
lastArgs = args;
if (frameId === null) {
frameId = requestAnimationFrame(() => {
frameId = null;
fn.apply(this, lastArgs);
});
}
};
}
module.exports = { debounce, debounceLeading, throttle, rafThrottle };Setting Up and Tearing Down
Turn fake timers on before each test and off after it. If one test leaves fake timers installed, or leaves timers in the queue, later tests in the same file can pick up callbacks they never scheduled.
// timing.test.js (setup section)
const { debounce, debounceLeading, throttle } = require('./timing');
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.clearAllTimers();
jest.useRealTimers();
});Jest offers several ways to move the clock. They differ in how far they go.
| Call | What it does | Use it when |
|---|---|---|
| `jest.advanceTimersByTime(ms)` | Moves the clock by `ms` and runs everything due on the way | You want to check behavior at exact time boundaries |
| `jest.runOnlyPendingTimers()` | Runs the timers queued right now, not ones they schedule | Code reschedules itself, such as polling loops |
| `jest.runAllTimers()` | Runs timers until the queue is empty, including new ones | You only care about the final state |
| `jest.getTimerCount()` | Returns how many timers are queued | Checking that `cancel` really cleared the timer |
| `jest.setSystemTime(t)` | Sets `Date.now()` without running timers | Testing timestamp logic from a known starting time |
For debounce and throttle, prefer advanceTimersByTime. You want to prove that nothing happens at wait - 1 and something happens at wait. runAllTimers jumps over that boundary.
Testing Trailing Debounce
These tests cover the main contract: one call, with the latest arguments, after a quiet period. Each new call restarts the wait.
describe('debounce', () => {
test('runs once with the last arguments after the wait', () => {
const fn = jest.fn();
const debounced = debounce(fn, 100);
debounced('a');
debounced('b');
debounced('c');
jest.advanceTimersByTime(99);
expect(fn).not.toHaveBeenCalled();
jest.advanceTimersByTime(1);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith('c');
});
test('each call restarts the wait', () => {
const fn = jest.fn();
const debounced = debounce(fn, 100);
debounced('a');
jest.advanceTimersByTime(60);
debounced('b');
jest.advanceTimersByTime(60);
expect(fn).not.toHaveBeenCalled();
jest.advanceTimersByTime(40);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith('b');
});
test('preserves this', () => {
const fn = jest.fn();
const obj = { run: debounce(fn, 50) };
obj.run(1);
jest.advanceTimersByTime(50);
expect(fn.mock.contexts[0]).toBe(obj);
});
test('cancel drops the pending call and its timer', () => {
const fn = jest.fn();
const debounced = debounce(fn, 100);
debounced('x');
expect(jest.getTimerCount()).toBe(1);
debounced.cancel();
expect(jest.getTimerCount()).toBe(0);
jest.runAllTimers();
expect(fn).not.toHaveBeenCalled();
});
test('flush runs the pending call now and returns its result', () => {
const fn = jest.fn((x) => x * 2);
const debounced = debounce(fn, 100);
debounced(21);
expect(debounced.flush()).toBe(42);
expect(fn).toHaveBeenCalledTimes(1);
jest.runAllTimers();
expect(fn).toHaveBeenCalledTimes(1);
});
});The second test is the one that catches the most common bug, a debounce that forgets to call clearTimeout. Without the clear, the first timer would still fire at 100 ms with 'a'. The this test uses mock.contexts, which Jest 28 added. On older versions, mock.instances records the same values. The last line of the flush test checks that flush cleared the timer. Without that check, a flush that forgot to clear would run the function a second time later.
Testing Leading Debounce
A leading-edge debounce is the opposite. The call should happen right away, with no clock movement at all.
describe('debounceLeading', () => {
test('fires immediately, then ignores calls until a quiet period', () => {
const fn = jest.fn();
const debounced = debounceLeading(fn, 100);
debounced('a');
expect(fn).toHaveBeenCalledWith('a');
jest.advanceTimersByTime(50);
debounced('b');
jest.advanceTimersByTime(99);
debounced('c');
expect(fn).toHaveBeenCalledTimes(1);
jest.advanceTimersByTime(100);
debounced('d');
expect(fn.mock.calls).toEqual([['a'], ['d']]);
});
});The call to 'c' happens 149 ms after the first call. It is still ignored, because 'b' restarted the quiet period. This test would catch an implementation that measured the wait from the first call instead of the most recent one.
Testing Throttle and the Date.now Trap
Modern fake timers advance Date.now() along with the timer queue, so the timestamp throttle works in tests without extra setup.
describe('throttle', () => {
test('fires on the leading edge and once more with the latest args', () => {
const fn = jest.fn();
const throttled = throttle(fn, 100);
throttled(1);
jest.advanceTimersByTime(50);
throttled(2);
jest.advanceTimersByTime(30);
throttled(3);
expect(fn.mock.calls).toEqual([[1]]);
jest.advanceTimersByTime(20);
expect(fn.mock.calls).toEqual([[1], [3]]);
});
test('first call fires immediately even when the clock starts at 0', () => {
jest.setSystemTime(0);
const fn = jest.fn();
const throttled = throttle(fn, 100);
throttled('first');
expect(fn).toHaveBeenCalledWith('first');
});
});The second test fails against the throttle in timing.js, and that failure is a real bug. The function starts with last = 0. In production, Date.now() is a large number, so now - last is always bigger than wait and the first call goes through. When the clock reads 0, as it can in tests or with performance.now()-style clocks, the first call computes remaining = 100 and gets deferred. Change the start value to let last = -Infinity; and the test passes. Fake timers let you choose the starting time, and that is how this kind of hidden assumption shows up.
Testing requestAnimationFrame Throttling
Modern fake timers also replace requestAnimationFrame when the environment has it. The jsdom environment does. A frame is simulated every 16 ms of virtual time.
/**
* @jest-environment jsdom
*/
const { rafThrottle } = require('./timing');
beforeEach(() => jest.useFakeTimers());
afterEach(() => jest.useRealTimers());
test('runs at most once per frame with the latest args', () => {
const fn = jest.fn();
const throttled = rafThrottle(fn);
throttled(10);
throttled(20);
throttled(30);
expect(fn).not.toHaveBeenCalled();
jest.advanceTimersByTime(16);
expect(fn.mock.calls).toEqual([[30]]);
});Put the docblock at the very top of its own test file. It sets the environment for the whole file. The default Node environment has no requestAnimationFrame, so the function under test would throw a ReferenceError.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Later tests see unexpected calls | Timers left queued or fake timers still installed | `clearAllTimers` and `useRealTimers` in `afterEach` |
| `runAllTimers` throws about too many timers | Code reschedules itself forever | Use `runOnlyPendingTimers` or `advanceTimersByTime` |
| Assertions after `await` see stale state | Promise callbacks are not timers | Use `await jest.advanceTimersByTimeAsync(ms)` (Jest 29.5+) |
| Throttle never fires on the leading edge | Clock started at 0 and `last = 0` | Start `last` at `-Infinity` |
| React state warnings about `act` | Timer callbacks update state outside `act` | Wrap clock advances in `act(() => jest.advanceTimersByTime(ms))` |
Vitest Equivalents
Vitest uses the same @sinonjs/fake-timers engine, so tests port by renaming.
| Jest | Vitest |
|---|---|
| `jest.useFakeTimers()` | `vi.useFakeTimers()` |
| `jest.advanceTimersByTime(ms)` | `vi.advanceTimersByTime(ms)` |
| `jest.runAllTimers()` | `vi.runAllTimers()` |
| `jest.setSystemTime(t)` | `vi.setSystemTime(t)` |
| `jest.fn()` | `vi.fn()` |
Exercise
A teammate's debounce test calls the debounced function three times, then calls jest.runAllTimers() and asserts the mock was called once with the last argument. The test passes, but production users report the handler firing too early. What gap in the test lets this bug through, and how would you close it?
Show answer
runAllTimers empties the whole queue, so the test only checks the final outcome and never checks when the call happened. A debounce that fires after the wrong delay (for example, it measures the wait from the first call, or uses a shorter delay) still passes. Use jest.advanceTimersByTime(wait - 1) and assert no call, then advance 1 ms and assert exactly one call. Add a test that makes a second call partway through the wait, to prove each call restarts the timer.
Exercise
Write a test proving that the trailing throttle from timing.js (with last fixed to -Infinity) makes no call at all after a single isolated call, meaning no trailing duplicate fires later.
Show answer
Call throttled('only'), assert fn was called once with 'only', then assert jest.getTimerCount() is 0. Next run jest.advanceTimersByTime(1000) and assert fn is still called once. The single call goes down the remaining <= 0 branch, which schedules no timer, so no trailing call can fire.
Exercise
Why does the throttle test work with jest.useFakeTimers() but fail when you switch to jest.useFakeTimers({ legacyFakeTimers: true })?
Show answer
Legacy fake timers replace setTimeout but not Date. The throttle reads Date.now() to compute remaining, so under legacy timers the clock it reads does not move when the test advances virtual time. Calls that should be outside the window are treated as inside it, and the trailing timer sets last to the real time. Modern fake timers advance Date.now() together with the timer queue.