{"record":{"id":"786227e6e0d15d20","repo":"vitest-dev/vitest","slug":"failed-to-mock-url-see-the-cause-for-more-in","errorCode":null,"errorMessage":"Failed to mock '${url}'. See the cause for more information.","messagePattern":"Failed to mock '(.+?)'\\. See the cause for more information\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/vitest/src/runtime/moduleRunner/nativeModuleMocker.ts","lineNumber":163,"sourceCode":"    if (transformedCode == null) {\n      return\n    }\n\n    const format = result.format?.startsWith('module') ? 'module' : 'commonjs'\n    try {\n      // we parse the module with es/cjs-module-lexer to find the original exports -- we assume the same ones are returned from the factory\n      // injecting new keys is not supported (and should not be advised anyway)\n      const exports = collectModuleExports(moduleId, transformedCode, format)\n      const manualMockedModule = createManualModuleSource(moduleId, exports)\n\n      return {\n        format: 'module',\n        source: manualMockedModule,\n        shortCircuit: true,\n      }\n    }\n    catch (cause) {\n      throw new Error(`Failed to mock '${url}'. See the cause for more information.`, { cause })\n    }\n  }\n\n  private processedModules = new Map<string, number>()\n\n  public checkCircularManualMock(url: string): void {\n    const filename = url.startsWith('file://') ? fileURLToPath(url) : url\n    const id = cleanUrl(normalizeModuleId(filename))\n    this.processedModules.set(id, (this.processedModules.get(id) ?? 0) + 1)\n    // the module is mocked and requested a second time, let's resolve\n    // the factory function that will redefine the exports later\n    if (this.originalModulePromises.has(id)) {\n      const factoryPromise = this.factoryPromises.get(id)\n      this.originalModulePromises.get(id)?.resolve({ __factoryPromise: factoryPromise })\n    }\n  }\n\n  private originalModulePromises = new Map<string, DeferPromise<any>>()","sourceCodeStart":145,"sourceCodeEnd":181,"githubUrl":"https://github.com/vitest-dev/vitest/blob/1fa9837ec26533512fdcad8baebf249771bd340a/packages/vitest/src/runtime/moduleRunner/nativeModuleMocker.ts#L145-L181","documentation":"When applying a manual mock (`vi.mock('mod', factory)`), Vitest parses the original module's source to collect its export names, then synthesizes a module shell whose exports the factory later overrides. If export collection or shell generation throws, this error wraps the cause. The catch is at nativeModuleMocker.ts:162-164.","triggerScenarios":"Calling `vi.mock('mod', () => ({ ... }))` where the original module's source cannot be parsed by `collectModuleExports` (es/cjs-module-lexer) or `createManualModuleSource`. The original error is attached as `cause`.","commonSituations":"Manual-mocking a TypeScript module on Node < 22.15 (no `module.stripTypeScriptTypes` — but that throws a dedicated 317 error before reaching here); module uses CJS syntax the lexer rejects; module is a JSON/native addon whose source is not JS; module has a syntax error; the mock factory is registered for a path that resolves to an unexpected file.","solutions":["Inspect `error.cause` for the underlying parse/export-collection failure.","If the module is TypeScript, ensure Node >= 22.15 (see error 317).","Match the factory's exports exactly to the original module's named exports (injecting new keys is unsupported per the comment at nativeModuleMocker.ts:151-152).","If the module is non-JS (JSON, WASM, native), use `vi.mock` with `vi.hoocked` redirection or alias instead.","Simplify the original module's export surface so the lexer can parse it."],"exampleFix":"// before\nvi.mock('./legacy-cjs', () => ({ oldApi: vi.fn() })) // lexer fails on CJS shape\n\n// after - provide a redirect via alias in config instead\n// test.server.config.ts\nresolve: { alias: { './legacy-cjs': './legacy-cjs-mock.ts' } }","handlingStrategy":"try-catch","validationCode":"try { collectModuleExports(moduleId, source, format) } catch (e) { throw new Error('manual mock will fail; check cause: ' + e.message) }","typeGuard":"null","tryCatchPattern":"try { vi.mock('./mod', factory) } catch (e) { if (/Failed to mock/.test(e.message)) { console.error(e.cause); /* alias or simplify exports */ } else throw e }","preventionTips":["Ensure the mocked module's named exports are statically analyzable by es/cjs-module-lexer.","Keep mock factory exports a strict subset of the original module's exports.","For non-JS modules, alias in Vite config instead of using `vi.mock`."],"tags":["mocker","manual-mock","parse-error","module-lexer"],"backgroundTag":null,"analyzedSha":"1fa9837ec26533512fdcad8baebf249771bd340a","analyzedAt":"2026-08-11T16:11:39.638Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}