| | |

Jest 13 ๐Ÿƒ Fake Timers โ€” jest.useFakeTimers() and @sinonjs/fake-timers

โฑ๏ธ Estimated read: 9 min | |

Jest’s fake timers replace the global setTimeout, setInterval, Date, and the related time functions with implementations the test controls. jest.useFakeTimers() installs the replacement, jest.advanceTimersByTime(ms) moves the clock forward, and jest.useRealTimers() restores the originals. The mechanism is a wrapper around @sinonjs/fake-timers, and the two APIs are nearly identical: the Jest functions delegate to the @sinonjs/fake-timers clock, and the library can be used directly when the test needs a feature the Jest wrapper does not expose.

This chapter covers the fake timer API, the @sinonjs/fake-timers relationship, and the date mocking that the timer replacement includes. The sections that follow walk through installing and advancing the timers, the runAllTimers and runOnlyPendingTimers methods, and the jest.setSystemTime call that fixes the clock for a date-dependent test.

Key point: jest.useFakeTimers() installs a @sinonjs/fake-timers clock behind the Jest API; jest.advanceTimersByTime(ms) moves the clock and runs due callbacks, jest.useRealTimers() restores the originals, and jest.setSystemTime(date) fixes the Date for a date-dependent test.


a. Installing and advancing the timers

The fake timer setup is a pair of calls: jest.useFakeTimers() before the test and jest.useRealTimers() after it. The beforeEach and afterEach hooks are the standard place for the pair.

beforeEach(() => {
  jest.useFakeTimers();
});

afterEach(() => {
  jest.useRealTimers();
});

test("calls the callback after the delay", () => {
  const callback = jest.fn();
  setTimeout(callback, 1000);

  jest.advanceTimersByTime(1000);

  expect(callback).toHaveBeenCalledTimes(1);
});

The advanceTimersByTime(ms) moves the clock forward by the given number of milliseconds and runs every timer whose deadline is within that window. A timer scheduled for 1000ms fires when the clock advances to 1000. A timer scheduled for 2000ms does not fire at 1000, and it fires on the next advance that reaches 2000.

The runAllTimers() method runs every pending timer, regardless of the delay, until there are none left. It is the method for a test that does not care about the exact timing, and it is the one that can loop forever if a timer schedules another timer indefinitely. The runOnlyPendingTimers() method runs only the timers that are currently pending, which is the safer choice for a timer that reschedules itself.

// Run every pending timer
jest.runAllTimers();

// Run only the currently pending timers
jest.runOnlyPendingTimers();

The advanceTimersToNextTimer() method advances the clock to the next timer’s deadline and runs it. It is the method for a test that needs to step through the timers one at a time, without knowing the exact delays.


b. The @sinonjs/fake-timers relationship

Jest’s fake timers are a wrapper around @sinonjs/fake-timers. The library is a standalone implementation of the same concept, and the Jest API delegates to it. The jest.useFakeTimers() call creates a @sinonjs/fake-timers clock, and the jest.advanceTimersByTime call is the library’s clock.tick .

The library can be used directly when the test needs a feature the Jest wrapper does not expose. The install function creates the clock, and the clock’s tick, next, and runAll methods are the primitives the Jest API wraps.

const FakeTimers = require("@sinonjs/fake-timers");

const clock = FakeTimers.install();
setTimeout(() => console.log("tick"), 1000);
clock.tick(1000); // logs "tick"
clock.uninstall();

The direct use is the pattern for a test that needs to control a timer library’s clock without the Jest global. The library also supports the shouldAdvanceTime option, which lets the clock advance with the real time, and the toFake option, which lists the functions to replace.

const clock = FakeTimers.install({
  now: new Date("2026-05-05T10:00:00Z"),
  toFake: ["setTimeout", "Date"],
});

The toFake option is the way to fake the Date but not the setTimeout, or vice versa. The now option is the initial clock value, which is the same as the jest.setSystemTime call.

The library’s timers object is the object the test uses when the clock is installed. The clock.tick and clock.next methods are the primitives, and the Jest advanceTimersByTime and advanceTimersToNextTimer are the wrappers.


c. Date mocking and the system time

The jest.useFakeTimers() replacement includes the Date object. The new Date() inside a test returns the faked clock’s current time, and Date.now() returns the same. The default is the current system time, and the jest.setSystemTime(date) call sets it to a fixed value.

test("formats the current date", () => {
  jest.useFakeTimers();
  jest.setSystemTime(new Date("2026-05-05T10:00:00Z"));

  expect(new Date().toISOString()).toBe("2026-05-05T10:00:00.000Z");

  jest.useRealTimers();
});

The setSystemTime is the method for a test that depends on the dateโ€”a relative time formatter, a token expiry check, a “today” label. The fixed time makes the test deterministic, and the useRealTimers() restores the real clock.

The jest.getRealSystemTime() returns the real time even when the fake clock is installed, which is the pattern for a test that needs to compare the faked time to the real one. The jest.now() returns the faked time.

The fake timers can be configured to exclude some functions with the doNotFake option. The option is the inverse of the library’s toFake, and it is the way to keep the real Date while faking the setTimeout.

jest.useFakeTimers({ doNotFake: ["Date"] });

The advanceTimersByTime is synchronous, and it does not flush the Promise microtasks. A test that combines a timer with an await needs the jest.advanceTimersByTimeAsync(ms) variant, which advances the clock and flushes the microtasks between the timer callbacks. The runAllTimersAsync and runOnlyPendingTimersAsync are the async versions of the two run methods.

test("resolves after the delay", async () => {
  const promise = new Promise((resolve) => {
    setTimeout(() => resolve("done"), 1000);
  });

  await jest.advanceTimersByTimeAsync(1000);

  await expect(promise).resolves.toBe("done");
});

Complete Example Session

// ============================================
// PART 1: THE SETUP
// ============================================
beforeEach(() => {
  jest.useFakeTimers();
});

afterEach(() => {
  jest.useRealTimers();
});

// ============================================
// PART 2: THE TIMER
// ============================================
describe("debounce", () => {
  test("calls after the delay", () => {
    const callback = jest.fn();
    setTimeout(callback, 1000);

    jest.advanceTimersByTime(1000);

    expect(callback).toHaveBeenCalledTimes(1);
  });

  test("does not call before the delay", () => {
    const callback = jest.fn();
    setTimeout(callback, 1000);

    jest.advanceTimersByTime(500);

    expect(callback).not.toHaveBeenCalled();
  });
});

// ============================================
// PART 3: THE ASYNC TIMER
// ============================================
describe("async", () => {
  test("resolves after the delay", async () => {
    const promise = new Promise((resolve) => {
      setTimeout(() => resolve("done"), 1000);
    });

    await jest.advanceTimersByTimeAsync(1000);

    await expect(promise).resolves.toBe("done");
  });
});

// ============================================
// PART 4: THE SYSTEM TIME
// ============================================
describe("date", () => {
  test("formats a fixed date", () => {
    jest.setSystemTime(new Date("2026-05-05T10:00:00Z"));
    expect(new Date().toISOString()).toBe("2026-05-05T10:00:00.000Z");
  });
});

The parts covered the setup, the synchronous timer, the async timer, and the system time.


Quick Reference

Timer API

CallEffect
jest.useFakeTimers()Install fake timers
jest.useRealTimers()Restore real timers
jest.advanceTimersByTime(ms)Advance and run due
jest.runAllTimers()Run every pending
jest.runOnlyPendingTimers()Run currently pending
jest.advanceTimersToNextTimer()Advance to the next
jest.advanceTimersByTimeAsync(ms)Advance and flush microtasks
jest.setSystemTime(date)Fix the clock

The @sinonjs/fake-timers API

CallEffect
FakeTimers.install()Create the clock
clock.tick(ms)Advance
clock.next()Advance to the next
clock.runAll()Run every pending
clock.uninstall()Restore

Date Mocking

CallReturns
jest.setSystemTime(date)Sets the clock
jest.getRealSystemTime()Real time
jest.now()Faked time

Best Practices

โœ… Do This:

// Install and restore in hooks
beforeEach(() => jest.useFakeTimers());
afterEach(() => jest.useRealTimers());                         // โœ…

// Use the async variant for a Promise
await jest.advanceTimersByTimeAsync(1000);                     // โœ…

// Fix the date for a date-dependent test
jest.setSystemTime(new Date("2026-05-05"));                    // โœ…

โŒ Don’t Do This:

// Advance without installing
jest.advanceTimersByTime(1000); // no fake timers active        // โŒ

// Use the sync variant for a Promise
jest.advanceTimersByTime(1000); await promise; // may hang      // โŒ

// Forget to restore
jest.useFakeTimers(); // leaks into other tests                 // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Timer does not fireNo useFakeTimersInstall before the test
Promise not resolvedSync advance usedadvanceTimersByTimeAsync
runAllTimers loopsTimer reschedules itselfrunOnlyPendingTimers
Date is realNo setSystemTimeFix the clock
Other tests hangTimers not restoreduseRealTimers in afterEach

Real-World Examples

1. Install

jest.useFakeTimers();

2. Advance

jest.advanceTimersByTime(1000);

3. Run all

jest.runAllTimers();

4. Run pending

jest.runOnlyPendingTimers();

5. Advance to next

jest.advanceTimersToNextTimer();

6. Async advance

await jest.advanceTimersByTimeAsync(1000);

7. Set system time

jest.setSystemTime(new Date("2026-05-05T10:00:00Z"));

8. Restore

jest.useRealTimers();

9. Partial faking

jest.useFakeTimers({ doNotFake: ["Date"] });

10. @sinonjs/fake-timers

const clock = FakeTimers.install();

Visual

Fake Timer Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  jest.useFakeTimers()                                   โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  setTimeout(cb, 1000)  โ†’ scheduled, not run             โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  jest.advanceTimersByTime(1000)                         โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  cb runs                                                โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  jest.useRealTimers()                                   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The @sinonjs/fake-timers Relationship

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  jest.useFakeTimers()                                   โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  FakeTimers.install()  โ—„โ”€โ”€ the library clock            โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  jest.advanceTimersByTime(ms)                           โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  clock.tick(ms)        โ—„โ”€โ”€ the library primitive        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Sync vs Async

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SYNC                           ASYNC                   โ”‚
โ”‚  advanceTimersByTime(ms)        advanceTimersByTimeAsync(ms)โ”‚
โ”‚    โ†’ runs timer callbacks         โ†’ runs callbacks      โ”‚
โ”‚    โ†’ does NOT flush microtasks    โ†’ flushes microtasks  โ”‚
โ”‚                                                         โ”‚
โ”‚  Use for mock call assertions   Use for Promise awaits  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Date Mocking

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  jest.useFakeTimers()                                   โ”‚
โ”‚  jest.setSystemTime(new Date("2026-05-05T10:00:00Z"))   โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  new Date() โ†’ 2026-05-05T10:00:00.000Z                  โ”‚
โ”‚  Date.now()  โ†’ the same timestamp                       โ”‚
โ”‚                                                         โ”‚
โ”‚  jest.useRealTimers() โ†’ real clock restored             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Installjest.useFakeTimers()
Restorejest.useRealTimers()
Advancejest.advanceTimersByTime(ms)
Run alljest.runAllTimers()
Run pendingjest.runOnlyPendingTimers()
Async advancejest.advanceTimersByTimeAsync(ms)
Fix the clockjest.setSystemTime(date)
Underlying library@sinonjs/fake-timers

Key takeaways:

  • Jest’s fake timers wrap @sinonjs/fake-timers. The jest.useFakeTimers() call installs the library’s clock, and the jest.advanceTimersByTime call is the library’s clock.tick. The library can be used directly when the test needs a feature the Jest wrapper does not expose.
  • advanceTimersByTime is synchronous and does not flush microtasks. A test that awaits a Promise resolved by a timer needs advanceTimersByTimeAsync, which flushes the microtasks between the timer callbacks.
  • runAllTimers can loop forever. A timer that reschedules itself keeps runAllTimers running until the test times out. runOnlyPendingTimers is the safer choice for a self-rescheduling timer.
  • setSystemTime fixes the date. A test that depends on the current date calls setSystemTime with a fixed value, and the new Date() and Date.now() inside the test return that value.
  • The install and restore belong in hooks. A beforeEach and afterEach pair ensures every test starts with the fake timers and ends with the real ones, so a test does not leak a fake clock into the next one.

Remember: Fake timers are the difference between a test that waits a second and a test that takes a millisecond. Install them in a beforeEach, advance them in the test, and restore them in an afterEach. Use the async variant when the test awaits a Promise, runOnlyPendingTimers when the timer reschedules itself, and setSystemTime when the test depends on the date. The fake clock is deterministic; the real clock is not.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!