Sub topic 11
Controlling Time with Fake Timers
Code that waits is slow and unreliable to test. A debounced search box waits 300 ms, a retry helper backs off for seconds, and a session expires after an hour. If tests wait in real time, the suite gets slow. If tests compare real clock readings, results change with machine load. Vitest's fake timers replace the clock with one your test controls. Time moves only when you tell it to, by exactly the amount you choose.
This chapter assumes you can write tests with describe, it, and expect. It also assumes you know how to use beforeEach and afterEach, create mock functions with vi.fn, and test promises with async/await.
How Fake Timers Work
vi.useFakeTimers() swaps the global timer functions for fake versions. These include setTimeout, setInterval, their clear* counterparts, and Date. Under the hood, Vitest uses the @sinonjs/fake-timers library. When your code calls setTimeout(fn, 1000), nothing is scheduled with the real event loop. The fake clock just records "run fn at time now + 1000." The callback runs only when the test advances the clock to that point or beyond.
Advancing is synchronous. When vi.advanceTimersByTime(1000) returns, every timer due within that window has already run, in order of due time.
Enabling and Restoring the Fake Clock
Turn fake timers on in beforeEach and off in afterEach. If you skip the restore step, later tests in the same file inherit a frozen clock. Then any real setTimeout in those tests, including ones inside libraries, never fires and the test hangs until it times out.
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 first assertion matters as much as the second. Checking that the callback has not run yet shows that the delay exists. Without that check, a version that called back immediately would also pass.
Choosing How to Advance Time
Vitest gives you several ways to move the clock. Pick the one that says what your test means.
| API | What it does | Use it when |
|---|---|---|
| `vi.advanceTimersByTime(ms)` | Moves the clock forward `ms` and runs every timer due in that window | You care about exact durations |
| `vi.advanceTimersToNextTimer()` | Jumps to the next scheduled timer and runs it | You want to step through timers one at a time |
| `vi.runOnlyPendingTimers()` | Runs the timers queued right now, but not timers they schedule | Intervals or timers that reschedule themselves |
| `vi.runAllTimers()` | Keeps running timers until the queue is empty | One-shot chains of timeouts |
| `vi.getTimerCount()` | Returns how many timers are still queued | Checking that cleanup cancelled everything |
| `vi.setSystemTime(date)` | Sets what `Date.now()` and `new Date()` return | Logic that depends on the calendar or the time of day |
Exact durations: testing a debounce
A debounce is a good fit for advanceTimersByTime, because the boundary is the behavior you want to test.
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
function debounce(fn, wait) {
let id
return (...args) => {
clearTimeout(id)
id = setTimeout(() => fn(...args), wait)
}
}
describe('debounce', () => {
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
it('calls once with the last arguments after the wait', () => {
const search = vi.fn()
const debounced = debounce(search, 300)
debounced('v')
vi.advanceTimersByTime(100)
debounced('vi')
vi.advanceTimersByTime(100)
debounced('vit') // last call at t=200, so it fires at t=500
vi.advanceTimersByTime(299)
expect(search).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
expect(search).toHaveBeenCalledTimes(1)
expect(search).toHaveBeenCalledWith('vit')
})
})Testing at 299 ms and then at 300 ms pins down the off-by-one edge. A real-time test can never check that reliably.
Intervals: avoid `runAllTimers`
setInterval reschedules itself forever. So does a setTimeout callback that sets a new timeout. vi.runAllTimers() keeps running until the queue is empty, which never happens here. Vitest stops after 10,000 timers and throws an error saying it aborted, which points to an infinite loop. Use advanceTimersByTime or runOnlyPendingTimers for intervals.
import { it, expect, vi, beforeEach, afterEach } from 'vitest'
function startPolling(check, interval) {
const id = setInterval(check, interval)
return () => clearInterval(id)
}
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
it('polls on each interval until stopped', () => {
const check = vi.fn()
const stop = startPolling(check, 1000)
vi.advanceTimersByTime(3000)
expect(check).toHaveBeenCalledTimes(3)
vi.runOnlyPendingTimers() // fires the one queued tick, not an endless chain
expect(check).toHaveBeenCalledTimes(4)
stop()
expect(vi.getTimerCount()).toBe(0)
})The final getTimerCount assertion checks that stop actually cleared the interval. Leaked timers are a common cause of memory leaks and of "process did not exit" warnings.
Faking the Current Date
While fake timers are active, Date is faked too. vi.setSystemTime sets the starting point. Advancing timers also moves Date.now() forward, so timers and the clock reading stay consistent.
import { it, expect, vi, beforeEach, afterEach } from 'vitest'
function isBusinessHours(now = new Date()) {
const hour = now.getUTCHours()
return hour >= 9 && hour < 17
}
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
it('tracks business hours as time passes', () => {
vi.setSystemTime(new Date('2026-01-05T08:59:00Z'))
expect(isBusinessHours()).toBe(false)
vi.advanceTimersByTime(60 * 1000)
expect(isBusinessHours()).toBe(true)
vi.advanceTimersByTime(8 * 60 * 60 * 1000)
expect(isBusinessHours()).toBe(false)
})Use UTC methods or a fixed time zone in date tests. A test that calls getHours() passes on a developer laptop in one zone and fails on a CI runner set to UTC. Setting the date in the test removes the clock as a source of nondeterminism, but it does not remove the time zone.
Timers and Promises Together
Synchronous advancing runs timer callbacks, but it does not wait for promises. Suppose a callback resolves a promise and the code after the await schedules another timer. advanceTimersByTime has already returned by the time that second timer exists. For promise-based code, use the async variants, vi.advanceTimersByTimeAsync and vi.runAllTimersAsync. They flush pending promise callbacks between timers.
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
async function retry(fn, attempts, delay) {
for (let i = 1; ; i++) {
try {
return await fn()
} catch (err) {
if (i >= attempts) throw err
await sleep(delay)
}
}
}
describe('retry', () => {
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
it('succeeds on the second attempt after one delay', async () => {
const fn = vi.fn()
.mockRejectedValueOnce(new Error('flaky'))
.mockResolvedValue('ok')
const promise = retry(fn, 3, 500)
await vi.advanceTimersByTimeAsync(500)
await expect(promise).resolves.toBe('ok')
expect(fn).toHaveBeenCalledTimes(2)
})
it('gives up after the last attempt', async () => {
const fn = vi.fn().mockRejectedValue(new Error('down'))
const promise = retry(fn, 3, 500)
const assertion = expect(promise).rejects.toThrow('down')
await vi.runAllTimersAsync()
await assertion
expect(fn).toHaveBeenCalledTimes(3)
})
})The second test attaches the rejects assertion before advancing time. If you advance first, the promise rejects while nothing is listening. Vitest then reports an unhandled rejection and may fail the run, even though your later assertion would have caught it.
Common Mistakes
- Forgetting
vi.useRealTimers(). Later tests hang or behave strangely. Always restore inafterEach. - Using
runAllTimerswith intervals. It hits the 10,000-timer limit. UseadvanceTimersByTimeorrunOnlyPendingTimers. - Using the sync API with async code. The test passes or fails depending on microtask timing. Use
advanceTimersByTimeAsyncorrunAllTimersAsync. - Only checking the "after" state. Also assert that nothing happened before the delay ran out.
- Expecting
process.nextTickorqueueMicrotaskto be faked. These are not faked by default. You can opt in through thetoFakeoption ofvi.useFakeTimers, but fakingnextTickcan break code that depends on it.
Exercise
A heartbeat(send) function calls setInterval(send, 5000) and returns a stop function. A teammate's test calls heartbeat(send) and then vi.runAllTimers(), and Vitest throws an error about aborting after 10000 timers. Explain why, and write the assertion steps that check send is called exactly twice in 10 seconds and that stopping leaves no timers queued.
Show answer
An interval reschedules itself after every tick, so the queue never empties and runAllTimers keeps going until it reaches its 10,000-timer limit. Use a bounded advance instead: const stop = heartbeat(send); vi.advanceTimersByTime(10000); expect(send).toHaveBeenCalledTimes(2); stop(); expect(vi.getTimerCount()).toBe(0), with fake timers enabled in beforeEach and restored in afterEach.
Exercise
In the retry example, why does the test that checks for failure create expect(promise).rejects.toThrow('down') before calling await vi.runAllTimersAsync(), and what goes wrong if you swap the two lines?
Show answer
Running the timers lets every attempt fail, so the promise rejects while the timers are being advanced. If no handler is attached at that moment, the rejection is unhandled and Vitest reports it as an error, which can fail the run even though the later assertion would have passed. Creating the assertion first attaches a handler to the promise before it rejects.