vitest-dev/vitest · error · Error

'toMatchScreenshot' cannot be used with "not"

Error message

'toMatchScreenshot' cannot be used with "not"

What it means

Thrown by `toMatchScreenshot` at toMatchScreenshot.ts:19-21 when called with `.not`. Visual regression produces a binary pass/fail plus reference/actual/diff artifacts; negating it has no meaningful semantics and would break the artifact-recording flow, so Vitest explicitly forbids it.

Source

Thrown at packages/browser/src/client/tester/expect/toMatchScreenshot.ts:20

import type { BrowserPage, ScreenshotMatcherOptions } from '../../../../context'
import type { ScreenshotMatcherArguments, ScreenshotMatcherOutput } from '../../../shared/screenshotMatcher/types'
import type { Locator } from '../locators'
import { recordArtifact } from 'vitest'
import { getBrowserState } from '../../utils'
import { serializeElement } from '../tester-utils'

const counters = new Map<string, { current: number }>([])

export default async function toMatchScreenshot(
  this: MatcherState,
  actual: BrowserPage | Element | Locator,
  nameOrOptions?: ScreenshotMatcherOptions | string,
  options: ScreenshotMatcherOptions = typeof nameOrOptions === 'object'
    ? nameOrOptions
    : {},
): AsyncMatcherResult {
  if (this.isNot) {
    throw new Error('\'toMatchScreenshot\' cannot be used with "not"')
  }

  if (this.task === undefined || this.currentTestName === undefined) {
    throw new Error('\'toMatchScreenshot\' cannot be used without test context')
  }

  const counterName = `${this.task.result?.repeatCount ?? 0}${this.testPath}${this.currentTestName}`
  let counter = counters.get(counterName)

  if (counter === undefined) {
    counter = { current: 0 }

    counters.set(counterName, counter)
  }

  counter.current += 1

  const name = typeof nameOrOptions === 'string'

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Remove the `.not` — express the expected visual state directly in the reference image.
  2. If you need to assert a screenshot does NOT match a specific baseline, maintain a different reference that represents the desired state.
  3. Use `toMatchScreenshot` with options like `diffMethod`/threshold to control tolerance instead of negation.

Example fix

// before
expect(page).not.toMatchScreenshot('home.png')

// after
expect(page).toMatchScreenshot('home.png')
Defensive patterns

Strategy: validation

Prevention

When it happens

Trigger: Writing `expect(page).not.toMatchScreenshot('home.png')` or any call where `this.isNot` is true. Triggered before any screenshot is taken, so it fails fast regardless of options.

Common situations: Developers reflexively chaining `.not.` to invert every matcher. Migrating from a custom snapshot matcher that allowed negation.

Related errors


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