vitest-dev/vitest · error · Error

snapshot function didn't throw

Error message

snapshot function didn't throw

What it means

Thrown by `getError` after it successfully invoked the `expected` function but the function returned without throwing. The snapshot-matching assertions for thrown errors require that the wrapped code actually throws an error to snapshot; if nothing is thrown, there is no error to capture and the assertion fails with this message.

Solutions

  1. Verify the function actually throws under the test's inputs (add a direct `toThrow()` check first).
  2. Update the test data/conditions so the throwing branch is exercised.
  3. If the behavior intentionally no longer throws, remove the snapshot assertion.

Example fix

// before
function safe(x) { return x }
expect(() => safe(1)).toThrowErrorMatchingSnapshot()

// after (assume the real throwing branch)
function risky(x) { if (x < 0) throw new Error('negative') }
expect(() => risky(-1)).toThrowErrorMatchingSnapshot()
Defensive patterns

Strategy: validation

Validate before calling

function expectThrows(fn) {
  let threw = false
  try { fn() } catch { threw = true }
  if (!threw) throw new Error('setup error: function did not throw')
  expect(fn).toThrowErrorMatchingSnapshot()
}

Prevention

When it happens

Trigger: Calling `expect(() => { /* nothing */ }).toThrowErrorMatchingSnapshot()` when the function body does not throw; the code path under test was refactored to no longer throw; conditional throw that wasn't triggered by the test inputs.

Common situations: Test written before the throwing branch existed; mock swallowing the throw; logic change that returns instead of throwing; data-dependent throw where the test data doesn't hit the throw path.

Related errors


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

Appendix: source

Thrown at packages/vitest/src/integrations/snapshot/chai.ts:46

  if (typeof expected !== 'function') {
    if (!promise) {
      throw new Error(
        `expected must be a function, received ${typeof expected}`,
      )
    }

    // when "promised", it receives thrown error
    return expected
  }

  try {
    expected()
  }
  catch (e) {
    return e
  }

  throw new Error('snapshot function didn\'t throw')
}

function getTestNames(test: Test) {
  return {
    filepath: test.file.filepath,
    name: getNames(test).slice(1).join(' > '),
    testId: test.id,
  }
}

function getAssertionName(assertion: Chai.Assertion): string {
  const name = chai.util.flag(assertion, '_name') as string | undefined
  if (!name) {
    throw new Error('Assertion name is not set. This is a bug in Vitest. Please, open a new issue with reproduction.')
  }
  return name
}

View on GitHub (pinned to 1fa9837ec2)