Reputation: 332
I get the following error running jest tests:
src/tests/components/ImageSearchApp.test.js
● Test suite failed to run
Cannot find module '@comp/Header' from 'src/components/ImageSearchApp.js'
Require stack:
src/components/ImageSearchApp.js
src/tests/components/ImageSearchApp.test.js
2 | import React from "react";
3 | /* ========= Components ============= */
> 4 | import Header from "@comp/Header";
| ^
5 | import { SearchImages } from "@cont/SearchImages";
6 | import Footer from "@comp/Footer";
7 | /* ========= Code ============= */
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:306:11)
at Object.<anonymous> (src/components/ImageSearchApp.js:4:1)
This started after I implemented resolved paths in my webpack.config.js
resolve: {
alias: {
"@root": path.resolve(__dirname, "./"),
"@src": path.resolve(__dirname, "src/"),
"@actions": path.resolve(__dirname, "src/actions"),
"@comp": path.resolve(__dirname, "src/components"),
"@cont": path.resolve(__dirname, "src/containers"),
"@img": path.resolve(__dirname, "src/img"),
"@reducers": path.resolve(__dirname, "src/reducers"),
"@selectors": path.resolve(__dirname, "src/selectors"),
"@store": path.resolve(__dirname, "src/store"),
"@tests": path.resolve(__dirname, "src/tests"),
"@consts": path.resolve(__dirname, "src/constants"),
},
},
My absolute paths work fine in my react components, I just cannot run tests. My jest.config.json looks like this:
{
"setupFiles": ["raf/polyfill", "<rootDir>/src/tests/setupTests.js"],
"snapshotSerializers": ["enzyme-to-json/serializer"]
}
That's how I run tests command in package.json:
"scripts": {
...,
"test": "jest --config=jest.config.json --watch",
...
},
Finally, my app structure:
App
|--dist
|--node_modules
|--src
| |--components
| |--tests
| |--compoenent.test.js
| |--setupTest.js
| |--app.js
|--jest.config.json
|--webpack.config.js
|--package.json
Can someone point me out the way how can I solve this issue. I want to use absolute paths in my webpack.config.js
Upvotes: 0
Views: 1445
Reputation: 580
In your jest.config.json
you need to set the moduleNameMapper property and map the same aliases you set in webpack.
You have also the option to set paths with modulePaths.
Example:
"moduleNameMapper": {
"@root/(.*)": "<rootDir>/$1",
"@src/(.*)": "<rootDir>/src/$1",
"@actions/(.*)": "<rootDir>/src/actions/$1",
}
Upvotes: 4