{"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/d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09/packages/vitest/src/runtime/moduleRunner/nativeModuleMocker.ts#L145-L181","documentation":"`NativeModuleMocker.loadManualMock` (`nativeModuleMocker.ts:163`) parses the original module to collect its export names (`collectModuleExports`) and then generates a manual-mock wrapper (`createManualModuleSource`). If either step throws (lexer/parse failure, unusual format), this `Error` wraps the cause. It affects `vi.mock('mod', factory)` — the factory itself isn't run yet; this is the export-shape detection on the real module.","triggerScenarios":"`vi.mock('mod', () => ({...}))` where `mod` fails export collection — unparseable source, exotic CJS/ESM shape, or a format the lexer doesn't recognize.","commonSituations":"Manual mocking a module with unusual export patterns; a CJS module with dynamic exports the lexer misses; an `.mjs`/`.cjs` ambiguity.","solutions":["Inspect `error.cause` for the specific lexer/parse failure.","Verify the real module loads normally first (import it in a non-test file) — if it can't load, fix the source.","If export collection is fundamentally broken for that module, avoid mocking it via the loader and inject the dependency another way (e.g. dependency injection in the SUT)."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"// Verify the real module loads before mocking it.\ntry {\n  await import('mod')\n} catch {\n  throw new Error('Cannot mock mod: the real module fails to load')\n}","typeGuard":null,"tryCatchPattern":"try {\n  vi.mock('mod', factory)\n} catch (e) {\n  if (e instanceof Error && /Failed to mock.*See the cause/.test(e.message)) {\n    console.error(e.cause)\n    // fall back to not mocking, or inject the dependency differently\n  } else throw e\n}","preventionTips":["Confirm the real module imports cleanly before mocking it.","Inspect error.cause to find the exact lexer/parse failure.","For modules with unusual export shapes, avoid loader-based mocking."],"tags":["mocking","manual-mock","parsing","native-mocker"],"analyzedSha":"d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09","analyzedAt":"2026-08-03T20:23:56.861Z","schemaVersion":2}