{"record":{"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/1fa9837ec26533512fdcad8baebf249771bd340a/packages/vitest/src/runtime/moduleRunner/nativeModuleMocker.ts#L96-L132","documentation":"When Vitest automocks a module (`vi.mock('mod')` with no factory, or `{ spy: true }`), it parses the module's source with acorn to enumerate exports, then synthesizes mocked values. If acorn cannot parse the transformed source, this error wraps the parse failure (original attached as `cause`). The catch is at nativeModuleMocker.ts:113-115.","triggerScenarios":"Calling `vi.mock('mod')` (automock) on a module whose source — after TypeScript stripping — is invalid JavaScript for acorn: uses syntax acorn rejects (e.g. decorators, stage-2 proposals without the right plugin), contains a syntax error, or the transformed source is empty/malformed. The `automockModule` call at nativeModuleMocker.ts:94-102 does the parse.","commonSituations":"Automocking a module with non-standard syntax not supported by acorn's latest ecmaVersion; mocking a built-in whose source synthesis is fine but a re-exported module fails; the module has a genuine syntax error that only surfaces under automock; `.stripTypeScriptTypes` produced output acorn still rejects (e.g. `enum` remnants).","solutions":["Inspect `error.cause` for the precise parse error and location.","Provide an explicit factory to skip automock parsing: `vi.mock('mod', () => ({ ... }))`.","Use `vi.mock('mod', { spy: true })` only if the module's runtime exports are introspectable.","Fix or simplify the syntax in the target module so acorn (ECMA latest) accepts it after TypeScript stripping.","If the module is third-party, prefer mocking at a higher level or aliasing to an ESM build."],"exampleFix":"// before\nvi.mock('./decorated-module') // automock fails to parse decorators\n\n// after\nvi.mock('./decorated-module', () => ({\n  doThing: vi.fn(),\n}))","handlingStrategy":"try-catch","validationCode":"try { parse(transformedSource, { sourceType: 'module', ecmaVersion: 'latest' }) } catch (e) { throw new Error('automock will fail; provide an explicit factory') }","typeGuard":"null","tryCatchPattern":"try { vi.mock('./mod') } catch (e) { if (/Cannot automock.*failed to parse/.test(e.message)) { vi.mock('./mod', () => ({ known: vi.fn() })) } else throw e }","preventionTips":["Prefer explicit factories for modules with non-standard syntax.","Keep mocked module source within acorn's accepted syntax (ECMA latest).","Validate the module parses with `acorn.parse` in a pre-test step if you automate mocking."],"tags":["mocker","automock","parse-error","acorn"],"backgroundTag":null,"analyzedSha":"1fa9837ec26533512fdcad8baebf249771bd340a","analyzedAt":"2026-08-11T16:11:39.638Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}