vitest-dev/vitest · error · Error

A function to advance timers was called but the timers APIs

Error message

A function to advance timers was called but the timers APIs are not mocked. Call `vi.useFakeTimers()` in the test file first.

What it means

Every timer-advancing API (`advanceTimersByTime`, `runAllTimers`, `runOnlyPendingTimers`, `advanceTimersToNextTimer`, `runAllTicks`, `getTimerCount`, etc.) is guarded by `_checkFakeTimers()`, which throws unless `vi.useFakeTimers()` has installed the fake clock (`_fakingTime === true`). This surfaces a forgotten setup call as an explicit error instead of silently operating on real timers.

Source

Thrown at packages/vitest/src/integrations/mock/timers.ts:260

        this._clock.setTickMode({ mode: 'interval', delta: interval })
      }
      else {
        throw new Error(`Invalid tick mode: ${mode}`)
      }
    }
  }

  configure(config: FakeTimersConfig): void {
    this._userConfig = config
  }

  isFakeTimers(): boolean {
    return this._fakingTime
  }

  private _checkFakeTimers() {
    if (!this._fakingTime) {
      throw new Error(
        'A function to advance timers was called but the timers APIs are not mocked. '
        + 'Call `vi.useFakeTimers()` in the test file first.',
      )
    }

    return this._fakingTime
  }
}

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Call `vi.useFakeTimers()` at the start of the test (or in `beforeEach`) before any timer-advance call.
  2. If you called `vi.useRealTimers()`, re-enable fakes with `vi.useFakeTimers()` before advancing again.
  3. Guard shared helpers so they enable fake timers before advancing.

Example fix

// before
it('fires callback', () => {
  const cb = vi.fn()
  setTimeout(cb, 1000)
  vi.advanceTimersByTime(1000) // throws
})
// after
it('fires callback', () => {
  vi.useFakeTimers()
  const cb = vi.fn()
  setTimeout(cb, 1000)
  vi.advanceTimersByTime(1000)
})
Defensive patterns

Strategy: validation

Validate before calling

import { vi } from 'vitest'
if (!vi.isFakeTimers()) {
  vi.useFakeTimers()
}
vi.advanceTimersByTime(1000)

Type guard

import { vi } from 'vitest'
// vi.isFakeTimers(): boolean — the public guard before advancing

Prevention

When it happens

Trigger: Calling `vi.advanceTimersByTime(n)`, `vi.runAllTimers()`, `vi.advanceTimersToNextTimer()`, `vi.runAllTicks()`, etc. without a preceding `vi.useFakeTimers()` in the same test, or after `vi.useRealTimers()` restored the real clock.

Common situations: Forgetting `vi.useFakeTimers()` in a new test, calling advance in `beforeAll` but using real timers per-test, or restoring real timers mid-test and then advancing.

Related errors


AI-assisted analysis of vitest-dev/vitest@d568f8ce37 (2026-08-03). Data as JSON: /data/errors/1d959c71d8ad6c92.json. Report an issue: GitHub.