Using with webpack

Jest can be used in projects that use webpack to manage assets, styles, and compilation. webpack does offer some unique challenges over other tools because it integrates directly with your application to allow managing stylesheets, assets like images and fonts, along with the expansive ecosystem of compile-to-JavaScript languages and tools.

A webpack example

Let’s start with a common sort of webpack config file and translate it to a Jest setup.

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.jsx?$/,
  6. exclude: ['node_modules'],
  7. use: ['babel-loader'],
  8. },
  9. {
  10. test: /\.css$/,
  11. use: ['style-loader', 'css-loader'],
  12. },
  13. {
  14. test: /\.gif$/,
  15. type: 'asset/inline',
  16. },
  17. {
  18. test: /\.(ttf|eot|svg)$/,
  19. type: 'asset/resource',
  20. },
  21. ],
  22. },
  23. resolve: {
  24. alias: {
  25. config$: './configs/app-config.js',
  26. react: './vendor/react-master',
  27. },
  28. extensions: ['.js', '.jsx'],
  29. modules: [
  30. 'node_modules',
  31. 'bower_components',
  32. 'shared',
  33. '/shared/vendor/modules',
  34. ],
  35. },
  36. };

If you have JavaScript files that are transformed by Babel, you can enable support for Babel by installing the babel-jest plugin. Non-Babel JavaScript transformations can be handled with Jest’s transform config option.

Handling Static Assets

Next, let’s configure Jest to gracefully handle asset files such as stylesheets and images. Usually, these files aren’t particularly useful in tests so we can safely mock them out. However, if you are using CSS Modules then it’s better to mock a proxy for your className lookups.

jest.config.js

  1. module.exports = {
  2. moduleNameMapper: {
  3. '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
  4. '<rootDir>/__mocks__/fileMock.js',
  5. '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
  6. },
  7. };

And the mock files themselves:

__mocks__/styleMock.js

  1. module.exports = {};

__mocks__/fileMock.js

  1. module.exports = 'test-file-stub';

Mocking CSS Modules

You can use an ES6 Proxy to mock CSS Modules:

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev identity-obj-proxy
  1. yarn add --dev identity-obj-proxy
  1. pnpm add --save-dev identity-obj-proxy

Then all your className lookups on the styles object will be returned as-is (e.g., styles.foobar === 'foobar'). This is pretty handy for React Snapshot Testing.

jest.config.js (for CSS Modules)

  1. module.exports = {
  2. moduleNameMapper: {
  3. '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
  4. '<rootDir>/__mocks__/fileMock.js',
  5. '\\.(css|less)$': 'identity-obj-proxy',
  6. },
  7. };

If moduleNameMapper cannot fulfill your requirements, you can use Jest’s transform config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that require('logo.jpg'); returns 'logo') can be written as:

fileTransformer.js

  1. const path = require('path');
  2. module.exports = {
  3. process(sourceText, sourcePath, options) {
  4. return {
  5. code: `module.exports = ${JSON.stringify(path.basename(sourcePath))};`,
  6. };
  7. },
  8. };

jest.config.js (for custom transformers and CSS Modules)

  1. module.exports = {
  2. moduleNameMapper: {
  3. '\\.(css|less)$': 'identity-obj-proxy',
  4. },
  5. transform: {
  6. '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
  7. '<rootDir>/fileTransformer.js',
  8. },
  9. };

We’ve told Jest to ignore files matching a stylesheet or image extension, and instead, require our mock files. You can adjust the regular expression to match the file types your webpack config handles.

Using with webpack - 图1tip

Remember to include the default babel-jest transformer explicitly, if you wish to use it alongside with additional code preprocessors:

  1. "transform": {
  2. "\\.[jt]sx?$": "babel-jest",
  3. "\\.css$": "some-css-transformer",
  4. }

Configuring Jest to find our files

Now that Jest knows how to process our files, we need to tell it how to find them. For webpack’s modules, and extensions options there are direct analogs in Jest’s moduleDirectories and moduleFileExtensions options.

jest.config.js

  1. module.exports = {
  2. moduleFileExtensions: ['js', 'jsx'],
  3. moduleDirectories: ['node_modules', 'bower_components', 'shared'],
  4. moduleNameMapper: {
  5. '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
  6. '\\.(gif|ttf|eot|svg)$': '<rootDir>/__mocks__/fileMock.js',
  7. },
  8. };

Using with webpack - 图2note

<rootDir> is a special token that gets replaced by Jest with the root of your project. Most of the time this will be the folder where your package.json is located unless you specify a custom rootDir option in your configuration.

Similarly, Jest’s counterpart for Webpack’s resolve.roots (an alternative to setting NODE_PATH) is modulePaths.

jest.config.js

  1. module.exports = {
  2. modulePaths: ['/shared/vendor/modules'],
  3. moduleFileExtensions: ['js', 'jsx'],
  4. moduleDirectories: ['node_modules', 'bower_components', 'shared'],
  5. moduleNameMapper: {
  6. '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
  7. '\\.(gif|ttf|eot|svg)$': '<rootDir>/__mocks__/fileMock.js',
  8. },
  9. };

And finally, we have to handle the webpack alias. For that, we can make use of the moduleNameMapper option again.

jest.config.js

  1. module.exports = {
  2. modulePaths: ['/shared/vendor/modules'],
  3. moduleFileExtensions: ['js', 'jsx'],
  4. moduleDirectories: ['node_modules', 'bower_components', 'shared'],
  5. moduleNameMapper: {
  6. '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
  7. '\\.(gif|ttf|eot|svg)$': '<rootDir>/__mocks__/fileMock.js',
  8. '^react(.*)$': '<rootDir>/vendor/react-master$1',
  9. '^config$': '<rootDir>/configs/app-config.js',
  10. },
  11. };

That’s it! webpack is a complex and flexible tool, so you may have to make some adjustments to handle your specific application’s needs. Luckily for most projects, Jest should be more than flexible enough to handle your webpack config.

Using with webpack - 图3tip

For more complex webpack configurations, you may also want to investigate projects such as: babel-plugin-webpack-loaders.

Using with webpack

In addition to installing babel-jest as described earlier, you’ll need to add @babel/preset-env like so:

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/preset-env
  1. yarn add --dev @babel/preset-env
  1. pnpm add --save-dev @babel/preset-env

Then, you’ll want to configure Babel as follows:

.babelrc

  1. {
  2. "presets": ["@babel/preset-env"]
  3. }

Using with webpack - 图4tip

Jest caches files to speed up test execution. If you updated .babelrc and Jest is not working as expected, try clearing the cache by running jest --clearCache.

Using with webpack - 图5tip

If you use dynamic imports (import('some-file.js').then(module => ...)), you need to enable the dynamic-import-node plugin.

.babelrc

  1. {
  2. "presets": [["env", {"modules": false}]],
  3. "plugins": ["syntax-dynamic-import"],
  4. "env": {
  5. "test": {
  6. "plugins": ["dynamic-import-node"]
  7. }
  8. }
  9. }

For an example of how to use Jest with webpack with React, you can view one here.