Sub topic 11
Controlling Time with Fake Timers
This chapter assumes you can write tests with describe and it, create mock functions with vi.fn, and use beforeEach and afterEach hooks. Code that relies on setTimeout, setInterval, or the current date is hard to test with real time. A test that waits a real second is slow, and a test that reads Date.now() gives a different result on every run. Fake timers replace these functions with versions controlled by the test, so you decide when time moves.
The working model
When you call vi.useFakeTimers(), Vitest swaps in fake versions of the global timer functions and Date. Scheduled callbacks go into a queue and do not run on their own. They run only when your test advances the fake clock.
A basic fake timer test
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
function delayedGreeting(callback) {
setTimeout(() => callback('hello'), 1000)
}
describe('delayedGreeting', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('calls back after one second', () => {
const callback = vi.fn()
delayedGreeting(callback)
expect(callback).not.toHaveBeenCalled()
vi.advanceTimersByTime(1000)
expect(callback).toHaveBeenCalledWith('hello')
})
})The afterEach hook restores real timers. If you skip it, later tests in the same file still run on the fake clock and break in ways that are hard to trace.
Advancing the clock
| Method | What it does |
|---|---|
| `vi.advanceTimersByTime(ms)` | Moves time forward by `ms` and runs every timer due in that window |
| `vi.advanceTimersToNextTimer()` | Jumps to the next scheduled timer and runs it |
| `vi.runOnlyPendingTimers()` | Runs the timers that are queued right now, but not timers they schedule |
| `vi.runAllTimers()` | Runs timers until the queue is empty |
| `vi.setSystemTime(date)` | Sets what `Date.now()` and `new Date()` return |
| `vi.getTimerCount()` | Returns how many timers are still queued |
Controlling the current date
vi.setSystemTime makes date-based logic deterministic:
import { it, expect, vi, afterEach } from 'vitest'
function isWeekend() {
const day = new Date().getDay()
return day === 0 || day === 6
}
afterEach(() => {
vi.useRealTimers()
})
it('detects a Saturday', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date(2026, 10, 28))
expect(isWeekend()).toBe(true)
})Common errors
- Infinite loops with
runAllTimers. AsetInterval, or a timeout that schedules itself again, never empties the queue. Vitest stops after 10,000 timers and throws an error. UseadvanceTimersByTimeorrunOnlyPendingTimersfor repeating timers. - Timers mixed with promises. If a callback awaits a promise before it sets the next timer, the synchronous advance methods run before that promise resolves. Use the async variants, such as
await vi.advanceTimersByTimeAsync(1000), which flush promises between timers. - Enabling fake timers too late. Timers created before
vi.useFakeTimers()use the real clock. Turn fake timers on before you call the code under test.
Exercise
A debounce(fn, 300) wrapper calls fn only after 300 ms pass with no new calls. You call the debounced function, advance 200 ms, call it again, then advance 200 ms. How many times has fn been called, and what single step makes it run once?
Show answer
Zero times. The second call reset the 300 ms wait, so only 200 ms have passed since that call. Call vi.advanceTimersByTime(100) and fn runs exactly once, which you check with expect(fn).toHaveBeenCalledTimes(1).
Exercise
Why can a test that uses vi.runAllTimers() on code with setInterval fail?
Show answer
The interval schedules itself again every time it runs, so the queue never empties. Vitest stops at its loop limit and throws. Advance by a fixed amount with vi.advanceTimersByTime, or use vi.runOnlyPendingTimers.