{"id":"7c18d35aa0cbc230","repo":"vitest-dev/vitest","slug":"cannot-automock-url-because-it-failed-to-pars","errorCode":null,"errorMessage":"Cannot automock '${url}' because it failed to parse.","messagePattern":"Cannot automock '(.+?)' because it failed to parse\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/vitest/src/runtime/moduleRunner/nativeModuleMocker.ts","lineNumber":114,"sourceCode":"        mockType,\n        code => parse(code, {\n          sourceType: 'module',\n          ecmaVersion: 'latest',\n        }),\n        { id: moduleId },\n      )\n      const transformed = ms.toString()\n      const map = ms.generateMap({ hires: 'boundary', source: moduleId })\n      const code = `${transformed}\\n//# sourceMappingURL=${genSourceMapUrl(map)}`\n\n      return {\n        format: 'module',\n        source: code,\n        shortCircuit: true,\n      }\n    }\n    catch (cause) {\n      throw new Error(`Cannot automock '${url}' because it failed to parse.`, { cause })\n    }\n  }\n\n  public loadManualMock(url: string, result: module.LoadFnOutput): module.LoadFnOutput | undefined {\n    const filename = url.startsWith('file://') ? fileURLToPath(url) : url\n    const moduleId = cleanUrl(normalizeModuleId(filename))\n    const mockedModule = this.getDependencyMock(moduleId)\n    // should not be possible\n    if (mockedModule?.type !== 'manual') {\n      console.warn(`Vitest detected unregistered manual mock ${moduleId}. This is a bug in Vitest. Please, open a new issue with reproduction.`)\n      return\n    }\n\n    if (isBuiltin(moduleId)) {\n      const builtinModule = getBuiltinModule(toBuiltin(moduleId))\n      const exports = Object.keys(builtinModule)\n      const manualMockedModule = createManualModuleSource(moduleId, exports)\n","sourceCodeStart":96,"sourceCodeEnd":132,"githubUrl":"https://github.com/vitest-dev/vitest/blob/d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09/packages/vitest/src/runtime/moduleRunner/nativeModuleMocker.ts#L96-L132","documentation":"`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).","triggerScenarios":"`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.","commonSituations":"Automocking a library using bleeding-edge syntax; automocking a TS module on an older Node; automocking a module with non-standard transforms.","solutions":["Switch to a manual factory: `vi.mock('mod', () => ({ doThing: vi.fn() }))` — no parsing of the original is needed.","Inspect `error.cause` for the exact parse failure and address the syntax.","Upgrade Node so TS stripping (if relevant) works, or pre-compile the module to plain JS."],"exampleFix":"// before\nvi.mock('./complex') // automock — fails to parse\n\n// after\nvi.mock('./complex', () => ({\n  doThing: vi.fn(),\n}))","handlingStrategy":"fallback","validationCode":"// Prefer a manual factory for modules that may not parse cleanly.\n// Only automock modules you know parse with acorn.\nvi.mock('./complex', () => ({\n  doThing: vi.fn().mockReturnValue(42),\n}))","typeGuard":null,"tryCatchPattern":"try {\n  vi.mock('mod')\n} catch (e) {\n  if (e instanceof Error && /Cannot automock.*failed to parse/.test(e.message)) {\n    vi.mock('mod', () => ({ /* explicit stubs */ }))\n  } else throw e\n}","preventionTips":["Use manual factories for modules with non-standard or bleeding-edge syntax.","Keep Node current so TS stripping works for automocked TS modules.","Inspect error.cause for the exact parse failure when automock breaks."],"tags":["mocking","automock","parsing","acorn","typescript","native-mocker"],"analyzedSha":"d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09","analyzedAt":"2026-08-03T20:23:56.861Z","schemaVersion":2}