Jest Cannot Find Module Error with Absolute Paths
I’m receiving the following error when running Jest:
Cannot find module ‘src/views/app’ from ‘index.jsx’
Error details:
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
at Object. (src/index.jsx:4:12)
Here is the relevant code:
import AppContainer from ‘src/views/app’;
Tests that run files containing only relative paths work correctly. How can I configure Jest to resolve modules with absolute paths without failing?
Hello Asheenaraghununan,
If you encounter the error Cannot find module ‘src/views/app’ from ‘index.jsx’ when running Jest, it’s likely due to the configuration of module directories in your package.json.
In your package.json, you have:
“moduleDirectories”: [
“node_modules”,
“src”
]
This configuration tells Jest to first look for modules in node_modules and, if not found, then look in the src directory.
To fix the error, you should adjust your import statement:
import AppContainer from ‘views/app’;
This path is considered absolute to the src directory, so you don’t need to navigate relative paths.
Alternatively, you can configure your root directory in moduleDirectories inside your package.json so that all your components can be imported as you prefer. For example:
“moduleDirectories”: [
“node_modules”,
“src”
]
By setting up your root directory correctly, you can ensure that Jest resolves your modules properly.
Hello Asheenaraghununan,
In my case, while running integration tests with all tests contained in the file src/int-test.spec.ts, I encountered issues with module paths. To resolve this, you can use the following solution:
Update your package.json configuration:
“jest”: {
…,
“moduleNameMapper”: {
“src/(.*)”: “/src/$1”
}
}
This configuration will map module imports starting with src/ to the appropriate path under /src, allowing Jest to correctly resolve the paths in your integration tests.
Hello Asheenaraghununan,
To resolve path issues in Jest, you can add the modulePaths configuration to your package.json:
“jest”: {
…
“modulePaths”: [
“”
],
…
}
This will ensure Jest looks for modules relative to the root directory of your project.