| | |

Vitest 13 🧪 Fake Timers — vi.useFakeTimers() and Controlling Time

⏱️ Estimated read: 8 min | |

Fake timers replace the global setTimeout, setInterval, Date, and the related time functions with implementations the test controls. vi.useFakeTimers() installs the replacement, vi.advanceTimersByTime(ms) moves the clock forward, and vi.useRealTimers() restores the originals. The mechanism is the same as Jest’s, and the reason is the same: a test that waits for a real setTimeout(1000) takes a second, and a suite of a hundred such tests takes a hundred seconds. The fake timers make the wait instantaneous and deterministic.

This chapter covers the fake timer API, the async variant that flushes microtasks, 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 vi.setSystemTime call that fixes the clock for a date-dependent test.

Key point: vi.useFakeTimers() replaces the timer functions and the Date; vi.advanceTimersByTime(ms) advances the clock and runs the due callbacks; vi.useRealTimers() restores the originals; and vi.advanceTimersByTimeAsync(ms) flushes the microtasks for a test that combines a timer with a Promise.


a. Installing and advancing the timers

The fake timer setup is a pair of calls: vi.useFakeTimers() before the test and vi.useRealTimers() after it. The beforeEach and afterEach hooks are the standard place for the pair, so every test in the file starts with the fake timers and ends with the real ones.

import { vi, beforeEach, afterEach, test, expect } from "vitest";

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

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

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

  vi.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
vi.runAllTimers();

// Run only the currently pending timers
vi.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 async variant and the microtask queue

The advanceTimersByTime method is synchronous, and it does not flush the Promise microtasks. A test that combines a timer with an await needs the async variant, which advances the clock and flushes the microtasks between the timer callbacks.

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

  await vi.advanceTimersByTimeAsync(1000);

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

The runAllTimersAsync and runOnlyPendingTimersAsync are the async versions of the two run methods. They are the correct form for a test that awaits a value that a timer produces, and the synchronous versions are the correct form for a test that asserts on a mock’s call count without awaiting anything.

The microtask flush is the detail that makes the difference. A setTimeout callback that resolves a Promise schedules the resolution on the microtask queue, and the synchronous advanceTimersByTime returns before the microtask runs. The async variant awaits the microtask flush, so the Promise is resolved by the time the next line runs.


c. Date mocking and the system time

The vi.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 vi.setSystemTime(date) call sets it to a fixed value.

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

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

  vi.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 vi.getMockedSystemTime() returns the current faked time, and vi.getRealSystemTime() returns the real time. The two are useful when a test needs to compare the faked time to the real one, or when the test’s setup needs to know which clock is active.

The fake timers can be configured to exclude some functions. The toFake option lists the functions to fake, and a test that needs the real Date but the fake setTimeout passes toFake: ["setTimeout", "setInterval"].

vi.useFakeTimers({ toFake: ["setTimeout", "setInterval"] });

The option is the escape hatch for a test that needs the real clock for one function and the fake clock for another. The default fakes every timer function and the Date, which is the behavior most tests want.


Complete Example Session

// ============================================
// PART 1: THE SETUP
// ============================================
import { vi, beforeEach, afterEach, describe, test, expect } from "vitest";

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

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

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

    vi.advanceTimersByTime(1000);

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

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

    vi.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 vi.advanceTimersByTimeAsync(1000);

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

// ============================================
// PART 4: THE SYSTEM TIME
// ============================================
describe("date", () => {
  test("formats a fixed date", () => {
    vi.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
vi.useFakeTimers()Install fake timers
vi.useRealTimers()Restore real timers
vi.advanceTimersByTime(ms)Advance and run due
vi.runAllTimers()Run every pending
vi.runOnlyPendingTimers()Run currently pending
vi.advanceTimersToNextTimer()Advance to the next
vi.advanceTimersByTimeAsync(ms)Advance and flush microtasks
vi.setSystemTime(date)Fix the clock

The Async Variants

SyncAsync
advanceTimersByTimeadvanceTimersByTimeAsync
runAllTimersrunAllTimersAsync
runOnlyPendingTimersrunOnlyPendingTimersAsync

Date Mocking

CallReturns
vi.setSystemTime(date)Sets the clock
vi.getMockedSystemTime()Faked time
vi.getRealSystemTime()Real time

Best Practices

✅ Do This:

// Install and restore in hooks
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());                           // ✅

// Use the async variant for a Promise
await vi.advanceTimersByTimeAsync(1000);                       // ✅

// Fix the date for a date-dependent test
vi.setSystemTime(new Date("2026-05-05"));                      // ✅

❌ Don’t Do This:

// Advance without installing
vi.advanceTimersByTime(1000); // no fake timers active          // ❌

// Use the sync variant for a Promise
vi.advanceTimersByTime(1000); await promise; // may hang        // ❌

// Forget to restore
vi.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

vi.useFakeTimers();

2. Advance

vi.advanceTimersByTime(1000);

3. Run all

vi.runAllTimers();

4. Run pending

vi.runOnlyPendingTimers();

5. Advance to next

vi.advanceTimersToNextTimer();

6. Async advance

await vi.advanceTimersByTimeAsync(1000);

7. Set system time

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

8. Restore

vi.useRealTimers();

9. Partial faking

vi.useFakeTimers({ toFake: ["setTimeout"] });

10. Real time check

vi.getRealSystemTime();

Visual

Fake Timer Flow

┌─────────────────────────────────────────────────────────┐
│  vi.useFakeTimers()                                     │
│         │                                               │
│         ▼                                               │
│  setTimeout(cb, 1000)  → scheduled, not run             │
│         │                                               │
│         ▼                                               │
│  vi.advanceTimersByTime(1000)                           │
│         │                                               │
│         ▼                                               │
│  cb runs                                                │
│         │                                               │
│         ▼                                               │
│  vi.useRealTimers()                                     │
└─────────────────────────────────────────────────────────┘

Sync vs Async

┌─────────────────────────────────────────────────────────┐
│  SYNC                           ASYNC                   │
│  vi.advanceTimersByTime(ms)     vi.advanceTimersByTimeAsync(ms) │
│    → runs timer callbacks         → runs callbacks        │
│    → does NOT flush microtasks    → flushes microtasks    │
│                                                         │
│  Use for mock call assertions   Use for Promise awaits   │
└─────────────────────────────────────────────────────────┘

Date Mocking

┌─────────────────────────────────────────────────────────┐
│  vi.useFakeTimers()                                     │
│  vi.setSystemTime(new Date("2026-05-05T10:00:00Z"))     │
│         │                                               │
│         ▼                                               │
│  new Date() → 2026-05-05T10:00:00.000Z                  │
│  Date.now()  → the same timestamp                       │
│                                                         │
│  vi.useRealTimers() → real clock restored               │
└─────────────────────────────────────────────────────────┘

Timer Run Methods

┌─────────────────────────────────────────────────────────┐
│  advanceTimersByTime(ms)  → advance and run due          │
│  runAllTimers()           → run every pending            │
│  runOnlyPendingTimers()   → run currently pending        │
│  advanceTimersToNextTimer() → advance to next deadline   │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Installvi.useFakeTimers()
Restorevi.useRealTimers()
Advancevi.advanceTimersByTime(ms)
Run allvi.runAllTimers()
Run pendingvi.runOnlyPendingTimers()
Async advancevi.advanceTimersByTimeAsync(ms)
Fix the clockvi.setSystemTime(date)

Key takeaways:

  • Fake timers replace the clock and the timer functions. vi.useFakeTimers() installs the replacement, advanceTimersByTime moves the clock forward, and useRealTimers restores the originals.
  • 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!