vitest-dev/vitest · error · Error

Cannot automock '${url}' because it failed to parse.

Error message

Cannot automock '${url}' because it failed to parse.

What it means

`NativeModuleMocker.loadAutomock` (`nativeModuleMocker.ts:114`) transforms the real module's source into a deep automock via `automockModule` (which parses exports with acorn and generates mock stubs). If the source can't be parsed — unsupported syntax, decorators, malformed code, or TS that wasn't fully stripped — it throws this `Error` with the parse failure as `cause`. This affects automocking (`vi.mock('mod')` with no factory).

Source

Thrown at packages/vitest/src/runtime/moduleRunner/nativeModuleMocker.ts:114

        mockType,
        code => parse(code, {
          sourceType: 'module',
          ecmaVersion: 'latest',
        }),
        { id: moduleId },
      )
      const transformed = ms.toString()
      const map = ms.generateMap({ hires: 'boundary', source: moduleId })
      const code = `${transformed}\n//# sourceMappingURL=${genSourceMapUrl(map)}`

      return {
        format: 'module',
        source: code,
        shortCircuit: true,
      }
    }
    catch (cause) {
      throw new Error(`Cannot automock '${url}' because it failed to parse.`, { cause })
    }
  }

  public loadManualMock(url: string, result: module.LoadFnOutput): module.LoadFnOutput | undefined {
    const filename = url.startsWith('file://') ? fileURLToPath(url) : url
    const moduleId = cleanUrl(normalizeModuleId(filename))
    const mockedModule = this.getDependencyMock(moduleId)
    // should not be possible
    if (mockedModule?.type !== 'manual') {
      console.warn(`Vitest detected unregistered manual mock ${moduleId}. This is a bug in Vitest. Please, open a new issue with reproduction.`)
      return
    }

    if (isBuiltin(moduleId)) {
      const builtinModule = getBuiltinModule(toBuiltin(moduleId))
      const exports = Object.keys(builtinModule)
      const manualMockedModule = createManualModuleSource(moduleId, exports)

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Switch to a manual factory: `vi.mock('mod', () => ({ doThing: vi.fn() }))` — no parsing of the original is needed.
  2. Inspect `error.cause` for the exact parse failure and address the syntax.
  3. Upgrade Node so TS stripping (if relevant) works, or pre-compile the module to plain JS.

Example fix

// before
vi.mock('./complex') // automock — fails to parse

// after
vi.mock('./complex', () => ({
  doThing: vi.fn(),
}))
Defensive patterns

Strategy: fallback

Validate before calling

// Prefer a manual factory for modules that may not parse cleanly.
// Only automock modules you know parse with acorn.
vi.mock('./complex', () => ({
  doThing: vi.fn().mockReturnValue(42),
}))

Try / catch

try {
  vi.mock('mod')
} catch (e) {
  if (e instanceof Error && /Cannot automock.*failed to parse/.test(e.message)) {
    vi.mock('mod', () => ({ /* explicit stubs */ }))
  } else throw e
}

Prevention

When it happens

Trigger: `vi.mock('mod')` (automock) where `mod` uses syntax acorn rejects (decorators, very new ES proposals, JSX without config), or malformed source, or TS on a Node that didn't strip types cleanly.

Common situations: Automocking a library using bleeding-edge syntax; automocking a TS module on an older Node; automocking a module with non-standard transforms.

Related errors


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