vitest-dev/vitest · error · Error

Snapshot cannot be used outside of test

Error message

Snapshot cannot be used outside of test

What it means

SnapshotClient.match throws 'Snapshot cannot be used outside of test' when the filepath option is falsy. The filepath ties a snapshot assertion to a test file; without it the snapshot cannot be located or written, so the assertion is rejected before any state lookup.

Example fix

// before
client.match({ name: 'test', received: value })
// after
client.match({ filepath: '/abs/test.ts', name: 'test', received: value })
Defensive patterns

Strategy: validation

Validate before calling

if (!filepath || typeof filepath !== 'string') {
  throw new Error('filepath is required for snapshot assertions')
}
client.match({ filepath, name, received })

Type guard

function hasFilepath(o: { filepath?: string }): o is { filepath: string } { return typeof o.filepath === 'string' && o.filepath.length > 0 }

Prevention

When it happens

Trigger: Calling snapshotClient.match with options.filepath omitted, empty, or undefined; invoking toMatchSnapshot-style logic outside a test context where filepath is not propagated.

Common situations: Using the snapshot API from a custom runner that does not set filepath; calling snapshot assertions in setup/global hooks; a wrapper that drops the filepath field; inline snapshot used in a script context.

Related errors


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

Appendix: source

Thrown at packages/snapshot/src/client.ts:134

  match(options: AssertOptions): MatchResult {
    const {
      filepath,
      name,
      testId = name,
      message,
      isInline = false,
      properties,
      inlineSnapshot,
      error,
      errorMessage,
      rawSnapshot,
      assertionName,
    } = options
    let { received } = options

    if (!filepath) {
      throw new Error('Snapshot cannot be used outside of test')
    }

    const snapshotState = this.getSnapshotState(filepath)
    const testName = [name, ...(message ? [message] : [])].join(' > ')

    // Probe first so we can mark as checked even on early return
    const expectedSnapshot = snapshotState.probeExpectedSnapshot({
      testName,
      testId,
      isInline,
      inlineSnapshot,
    })

    if (typeof properties === 'object') {
      if (typeof received !== 'object' || !received) {
        expectedSnapshot.markAsChecked()
        throw new Error(
          'Received value must be an object when the matcher has properties',

View on GitHub (pinned to 1fa9837ec2)