Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring Jest to mimic webpack resolve root and resolve alias

Tags:

webpack

jestjs

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?

like image 874
Krustal Avatar asked Oct 17 '15 19:10

Krustal


People also ask

Does Jest use webpack config?

Luckily for most projects, Jest should be more than flexible enough to handle your webpack config. For more complex webpack configurations, you may also want to investigate projects such as: babel-plugin-webpack-loaders.

What is $1 Jest config?

In the right side's expression The $1 is replacement syntax to refer to capture group one. Had you two sets of parens on the left side, then you could refer to group one ( $1 ) and group two ( $2 ) in the replacement expression. Capture groups are numbered left-to-right, outermost to innermost.

What is Jest moduleNameMapper?

2. moduleNameMapper [Object] (Default: null) This configuration holds the key to file mocking. By using this configuration all the external asset files like images and style files will be mocked, as these files are not intended to be tested. So, while running test cases, only the the mock files are imported.


2 Answers

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"], 
    ...
}
like image 129
Rob Squires Avatar answered Sep 24 '22 20:09

Rob Squires


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).

like image 21
kompot Avatar answered Sep 21 '22 20:09

kompot