{"id":"c76fafca110a9642","repo":"jestjs/jest","slug":"cannot-find-module-modulename-from-relativ","errorCode":null,"errorMessage":"Cannot find module '${moduleName}' from '${relativePath}'","messagePattern":"Cannot find module '(.+?)' from '(.+?)'","errorType":"exception","errorClass":"ModuleNotFoundError","httpStatus":null,"severity":"error","filePath":"packages/jest-resolve/src/resolver.ts","lineNumber":461,"sourceCode":"  }\n\n  /**\n   * _getHasteModulePath attempts to return the path to a haste module.\n   */\n  private _getHasteModulePath(moduleName: string) {\n    const parts = moduleName.split('/');\n    const hastePackage = this.getPackage(parts.shift()!);\n    if (hastePackage) {\n      return path.join(path.dirname(hastePackage), ...parts);\n    }\n    return null;\n  }\n\n  private _throwModNotFoundError(from: string, moduleName: string): never {\n    const relativePath =\n      slash(path.relative(this._options.rootDir, from)) || '.';\n\n    throw new ModuleNotFoundError(\n      `Cannot find module '${moduleName}' from '${relativePath}'`,\n      moduleName,\n    );\n  }\n\n  private _getMapModuleName(matches: RegExpMatchArray | null) {\n    return matches\n      ? (moduleName: string) =>\n          moduleName.replaceAll(\n            /\\$(\\d+)/g,\n            (_, index) => matches[Number.parseInt(index, 10)] || '',\n          )\n      : (moduleName: string) => moduleName;\n  }\n\n  private _isAliasModule(moduleName: string): boolean {\n    const moduleNameMapper = this._options.moduleNameMapper;\n    if (!moduleNameMapper) {","sourceCodeStart":443,"sourceCodeEnd":479,"githubUrl":"https://github.com/jestjs/jest/blob/f49721c78e195558b40913977c9230f5b7f559d8/packages/jest-resolve/src/resolver.ts#L443-L479","documentation":"ModuleNotFoundError thrown by Resolver._throwModNotFoundError after every resolution strategy (moduleNameMapper, cache, haste modules, node_modules via defaultResolver, haste packages) has been exhausted. The message names the missing module and the file that tried to import it, which is the canonical Jest 'cannot find module' diagnostic.","triggerScenarios":"A test or source file calls `require('x')` / `import 'x'` where `x` is not installed, not on NODE_PATH, not matched by moduleNameMapper, and not registered as a haste module. Also thrown when a moduleNameMapper regex matches but the mapped target itself does not resolve (mapper matches are strict — no fallback).","commonSituations":"Forgot to `npm install` a dependency; typo in module name; moduleNameMapper regex too greedy and capturing the wrong path; `moduleDirectories`/`roots` misconfigured so node_modules isn't searched; importing a workspace package whose name differs from its directory; Node version mismatch where a builtin was renamed; case-sensitivity differences between macOS (case-insensitive) and Linux CI.","solutions":["Run `npm ls <moduleName>` or `ls node_modules/<moduleName>` to confirm the package is installed at the version expected.","Check `jest.config` `moduleNameMapper` — if a regex matches this import, verify the replacement path resolves from `rootDir`.","Verify `moduleDirectories` (defaults to `['node_modules']`) and `roots` include the directories you expect Jest to search.","On case-sensitive filesystems (Linux CI), correct the import casing to match the installed package name exactly.","For workspace/monorepo packages, ensure the package is built (`main`/`exports` field points to an existing file) and linked via the workspace tool."],"exampleFix":"// before — jest.config.js\nmodule.exports = { moduleNameMapper: { '^@app/(.*)$': 'src/$1' } };\n// import '@app/utils/foo' fails because 'src/utils/foo' doesn't exist\n\n// after — map to the correct root\nmodule.exports = { moduleNameMapper: { '^@app/(.*)$': '<rootDir>/src/$1' } };","handlingStrategy":"validation","validationCode":"// In a setup file or pre-test script — confirm modules resolve\nconst resolver = require('jest-resolve');\nfunction assertResolvable(fromDir, name, opts) {\n  const r = new resolver.Resolver(opts, {});\n  if (!r.resolveModule(fromDir, name)) {\n    throw new Error(`Pre-check: '${name}' does not resolve from ${fromDir}`);\n  }\n}","typeGuard":null,"tryCatchPattern":"// Wrap a dynamic require you suspect may fail\ntry {\n  require('maybe-missing');\n} catch (e) {\n  if (e.message.includes(\"Cannot find module\")) {\n    // provide a fallback or fail with a clearer message\n  }\n  throw e;\n}","preventionTips":["Run `npm ls <pkg>` in CI as a pre-test step for critical dependencies.","Keep moduleNameMapper patterns specific (anchored) to avoid accidental greedy matches.","Lint import paths with eslint-plugin-import to catch typos and missing extensions early.","On case-sensitive CI, enforce case-correct imports via eslint import rules."],"tags":["resolver","module-not-found","config","modulenamemapper"],"analyzedSha":"f49721c78e195558b40913977c9230f5b7f559d8","analyzedAt":"2026-08-03T20:16:28.571Z","schemaVersion":2}