Jest: Webpack externals

Created on 11 Sep 2017  Â·  4Comments  Â·  Source: facebook/jest

I have a Webpack bundle that has as externals 'react' and 'react-dom'.

const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        libraryTarget: "umd",
        library: "Example"
    },
    module: {
        loaders: [
          { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
          { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
        ]
    },
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};

When I include the Webpack bundle in my test I the following error:

Cannot find module 'ReactDOM' from 'bundle.js'

I tried to without success:

  • creating a manual mock as described here
  • setting Jest paramaters in package.json:
...
    "moduleDirectories": ["node_modules", "bower_components", "shared"],
    "moduleNameMapper": {
      "React": "react",
      "ReactDOM": "react-dom"
    }
...

I cannot find any documentation on the use of Webpack externals.

Does Jest support Webpack externals, and if so, how should they be configured?

Most helpful comment

Is that documented anywhere? It's a pretty common use case to build react libraries and test them with Jest.

All 4 comments

Jest runs without Webpack, so you need to provide the global React and ReactDOM or just use npm modules. Also, this is not a help forum – you'll find our help page useful :)

@thymikee sorry for wrongly posting this question, but for my understanding and for documentation purposes: how do I provide the global React and ReactDOM variables in Jest?

@joostmeijles Like, (in jest.config.js):

module.exports = {
  globals: {
    React: require('react'),
    ReactDOM: require('react-dom')
  },
  ...
}

Is that documented anywhere? It's a pretty common use case to build react libraries and test them with Jest.

Was this page helpful?
0 / 5 - 0 ratings