Jest 13 ๐ Fake Timers โ jest.useFakeTimers() and @sinonjs/fake-timers
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
| Call | Effect |
|---|---|
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
| Call | Effect |
|---|---|
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
| Call | Returns |
|---|---|
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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Timer does not fire | No useFakeTimers | Install before the test |
| Promise not resolved | Sync advance used | advanceTimersByTimeAsync |
runAllTimers loops | Timer reschedules itself | runOnlyPendingTimers |
| Date is real | No setSystemTime | Fix the clock |
| Other tests hang | Timers not restored | useRealTimers 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
| Item | Value |
|---|---|
| Install | jest.useFakeTimers() |
| Restore | jest.useRealTimers() |
| Advance | jest.advanceTimersByTime(ms) |
| Run all | jest.runAllTimers() |
| Run pending | jest.runOnlyPendingTimers() |
| Async advance | jest.advanceTimersByTimeAsync(ms) |
| Fix the clock | jest.setSystemTime(date) |
| Underlying library | @sinonjs/fake-timers |
Key takeaways:
- Jest’s fake timers wrap
@sinonjs/fake-timers. Thejest.useFakeTimers()call installs the library’s clock, and thejest.advanceTimersByTimecall is the library’sclock.tick. The library can be used directly when the test needs a feature the Jest wrapper does not expose. advanceTimersByTimeis synchronous and does not flush microtasks. A test that awaits a Promise resolved by a timer needsadvanceTimersByTimeAsync, which flushes the microtasks between the timer callbacks.runAllTimerscan loop forever. A timer that reschedules itself keepsrunAllTimersrunning until the test times out.runOnlyPendingTimersis the safer choice for a self-rescheduling timer.setSystemTimefixes the date. A test that depends on the current date callssetSystemTimewith a fixed value, and thenew Date()andDate.now()inside the test return that value.- The install and restore belong in hooks. A
beforeEachandafterEachpair 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.
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!