Using with webpack

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

    webpack.config.js

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

    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';

    You can use an to mock CSS Modules:

    • npm
    • Yarn
    • pnpm
    1. npm install --save-dev identity-obj-proxy
    1. yarn add --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 .

    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. },

    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. };

    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.

    tip

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

    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 is located unless you specify a custom option in your configuration.

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

    jest.config.js

    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.

    tip

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

    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.

    tip

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

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