Code Reference

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

APIRole
jest.useFakeTimers()Enable fakes
jest.useRealTimers()Restore real
advanceTimersByTimeFast-forward ms
runAllTimersFlush all
runOnlyPendingTimersCurrent queue
modern / legacyFake 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.
  • runAllTimers infinite loops on recurring intervals.
  • User-event / RTL needs advanceTimers coordination.
  • Spying on Date while also faking timers — pick one strategy.

On this page