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

Thrown by `FakeTimers._checkFakeTimers()` (and therefore by every timer-advancing API such as `runAllTimers`, `advanceTimersByTime`, `runOnlyPendingTimers`) when `_fakingTime` is false — i.e. `vi.useFakeTimers()` was never called (or was reset). The message directs the developer to enable fake timers first.

Solutions

  1. Add `vi.useFakeTimers()` at the top of the test (or in `beforeEach`) before any `vi.advanceTimers*`/`runAllTimers` call.
  2. If you previously called `vi.useRealTimers()`, re-enable fakes with `vi.useFakeTimers()` before advancing.
  3. Guard shared helpers with `if (vi.isFakeTimersActive?.()) { ... }` or accept that fake timers must be set up by the caller.

Example fix

// before
it('flushes', () => {
  vi.advanceTimersByTime(1000)
})

// after
it('flushes', () => {
  vi.useFakeTimers()
  vi.advanceTimersByTime(1000)
})
Defensive patterns

Strategy: validation

Validate before calling

function advanceSafely(ms) {
  if (!vi.isFakeTimersActive()) {
    vi.useFakeTimers()
  }
  vi.advanceTimersByTime(ms)
}

Type guard

function fakeTimersActive() {
  return typeof vi.isFakeTimersActive === 'function' && vi.isFakeTimersActive()
}

Prevention

When it happens

Trigger: Calling `vi.runAllTimers()` / `vi.advanceTimersByTime(1000)` / `vi.advanceTimersToNextTimer()` without first calling `vi.useFakeTimers()`; calling after `vi.useRealTimers()`; calling before `vi.useFakeTimers()` in a test that imported a module using real timers.

Common situations: Forgetting the `vi.useFakeTimers()` call; helper utilities that advance timers but assume the test set them up; shared `beforeEach` that conditionally enables fake timers; calling `vi.useRealTimers()` mid-test then advancing.

Related errors


AI-assisted analysis of vitest-dev/vitest@1fa9837ec2 (2026-08-11). Data as JSON: /api/errors/1d959c71d8ad6c92. Report an issue: GitHub.

Appendix: 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 1fa9837ec2)