Timers
Jest · Reference cheat sheet
Timers
Jest · Reference cheat sheet
📋 Overview
Fake timers control setTimeout, setInterval, and (with modern APIs) Date. Use them to test debouncing, polling, and animations without real waits.
🔧 Core concepts
| API | Role |
|---|---|
jest.useFakeTimers() | Enable fakes |
jest.useRealTimers() | Restore real |
advanceTimersByTime | Fast-forward ms |
runAllTimers | Flush all |
runOnlyPendingTimers | Current queue |
modern / legacy | Fake timer impl |
Jest 29 defaults to modern @sinonjs/fake-timers.
💡 Examples
Debounce:
jest.useFakeTimers();
test('debounces', () => {
const fn = jest.fn();
const d = debounce(fn, 500);
d();
d();
expect(fn).not.toHaveBeenCalled();
jest.advanceTimersByTime(500);
expect(fn).toHaveBeenCalledTimes(1);
});
afterEach(() => {
jest.useRealTimers();
});Async + timers:
test('polls', async () => {
jest.useFakeTimers();
const p = waitForReady(); // uses setTimeout
await jest.advanceTimersByTimeAsync(1000);
await expect(p).resolves.toBe(true);
});Fake Date:
jest.useFakeTimers({ now: new Date('2020-01-01') });
expect(Date.now()).toBe(new Date('2020-01-01').getTime());Config:
// jest.config.js
fakeTimers: { enableGlobally: false },⚠️ Pitfalls
- Forgetting
useRealTimers→ later tests hang or flake. - Mixing real promises with fake timers without
advanceTimersByTimeAsync. runAllTimersinfinite loops on recurring intervals.- User-event / RTL needs
advanceTimerscoordination. - Spying on
Datewhile also faking timers — pick one strategy.