Home > Blockchain >  How do you use Jest on Webpack?
How do you use Jest on Webpack?

Time:08-09

I took a look the official document Using with webpack · Jest , but I don't understand.. where's the Jest part in the example?? It looks a normal webpack config file without a Jest to me.

I also took a look some other tutorials e.g. Web Component Tutorial => Webpack and Jest or What happened to setupTestFrameworkScriptFile? · Issue #2558 · facebook/jest, these articles say adding setupTestFrameworkScriptFile: "<rootDir>/bin/jest.js",, so basically my setup is like the below:

  • ./src/test/sum.test.js
function sum(a, b) {
  return a   b;
}

test('adds 1   2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});
  • ./webpack.config.js
module.exports = {
  mode: mode,
  devtool: (mode === 'development') ? 'inline-source-map' : false,

  setupTestFrameworkScriptFile: "<rootDir>/bin/jest.js", // <--- added this
  ..

Now running npx webpack serve, gets an error:

Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
 - configuration has an unknown property 'setupTestFrameworkScriptFile'. These properties are valid:

What am I doing wrong here? Just, how can you integrate a simple set of Jest tasks to Webpack?? Thanks.

CodePudding user response:

The official example Using with webpack shows us how to find and transform test files, exclude node_modules and some module and files, and handle static assets, CSS Modules, module alias when running the test like webpack when using jest. They give a webpack config example and translate the configs to a jest setup.

Webpack can transform your code using babel-loader via loaders configuration, jest use transform configuration to do the same thing.

Webpack uses url-loader and file-loader handle static assets. But for testing

usually, these files aren't particularly useful in tests so we can safely mock them out

So we can use the jestjs moduleNameMapper configuration to mock the static assets.

Webpack doesn't have a setupTestFrameworkScriptFile configuration, it's jest's configuration.

There two npm scripts:

"build": "webpack",
"test": "jest"

You should build and serve your code using webpack, running the test code using jest. They have their own configurations. It's just that some configurations do the same thing.

  • Related