I am working on setting up a project with Webpack & Jest. At the moment Webpack resolve configurations cause complications with Jest tests. In my webpack config I have the following options set:
resolve: {
root: [__dirname + "/src/" ],
extensions: ['', '.js', '.coffee', '.jsx', '.css', '.scss', '.svg']
}
This lets me require assets and modules with:
import UnknownImg from 'assets/unknown';
The above actually lives (relative to my project root) src/assets/unknown.svg
.
However, when I run the test for files with lines like the above I get errors when resolving the path to that required module/asset.
Error: /Users/byronsm/dev/nerve-center/src/components/organisms/system_status.jsx: Cannot find module 'assets/unknown' from '/Users/byronsm/dev/nerve-center/src/components/organisms'
In this case it appears to be doing a relative lookup of the imported module path. Is there a way for me to get Jest to behave the same as Webpack?
A solution is now provided in the official jest docs. See Webpack Tutorial.
In short, add the modulePaths
option to your jest config inpackage.json
:
"jest": {
"modulePaths": ["src"],
...
}
After a good nights rest I looked at this again and realized it wasn't a Jest configuration but node. The best way to mimic the behavior of the resolve.root config in webpack is to set the environment variable NODE_PATH
to the same directory when running jest
:
NODE_PATH=src jest
That doesn't really solve the issue of multiple directories it solved my issue. This article helped me understand the solution a little better https://gist.github.com/branneman/8048520.
You can use Jest 20+ resolver
option and plug it with jest-webpack-resolver
This package does not seem mature (several days old) but does the job for me. Also, as of now, it requires Jest config to be in a separate jest.config.js
file or provided via CLI (does not support package.json
).
Jestpack aims to solve this problem by building your test files with Webpack before running them with Jest. This means any special module resolution rules or loaders in your Webpack config will work in the exact same way as your production build.
I wrote mimic-webpack
to take a webpack config and hook into node's require in order to resolve paths just like webpack. I haven't tested it with jest, but it should work with any spec runner that runs on node and will even support simple loaders.
Jest version 23.6.0
:
Add this line to jest.config.js
moduleDirectories: ["node_modules", "src"],
or in package.json
"jest": {
"moduleDirectories": ["node_modules", "src"],
...
}