I am trying to setup Jest with my webpack project. When I run my tests, Jest complains it cannot read es6 code. Babel seems to not transform my test files.
I have tried
I have some useful information that can be used as a reference for those who see this problem later.
By default, transformIgnorePatterns in jest config was ["/node_modules/", "\.pnp\.[^\/]+$"]
If some guys issue was caused by some code in node_modules and do not overwrite this value, babel-jest still not working.
Maybe the correct value like this "/node_modules/(?!(your-third-part-es-module-code|others-es-lib))"
You need to do two things:
Create a Babel config file (babel.config.js
):
This is necessary because babel-jest
relies on a traditional Babel config file, not webpack. Since version 7 Babel has supported JS configs as babel.config.js
.
When using a JS Babel config (as opposed to a .babelrc
, for example) Jest also compiles modules in node_modules
. AFAIK by convention this must be in the root of your project, alongside the jest configuration file.
Here is a config based on the Babel options in your webpack.config.js
file:
// babel.config.js
module.exports = {
presets: [
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-flow',
],
plugins: [
'babel-plugin-styled-components',
'@babel/plugin-proposal-class-properties',
]
}
Install the babel-core
bridge version:
npm install babel-core@7.0.0-bridge.0 --save-dev
From github.com/babel/babel-bridge:
This repo holds what we're calling a "bridge" package that is meant to ease the transition for libraries that use "babel-core" as a peer dependency for Babel 6.
The issue with Babel 7's transition to scopes is that if a package depends on Babel 6, they may want to add support for Babel 7 alongside. Because Babel 7 will be released as @babel/core instead of babel-core, maintainers have no way to do that transition without making a breaking change. e.g.
I ran into a similar situation where I wanted to test a React component .js
file with jest, but it was failing because the component imported a .css
stylesheet. I was using Babel with Webpack.
As per the accepted answer @sdgluck, I had to add a babel.config.js
:
1.
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react']
};
2. I also installed babel-jest
as a dev-dependency
3. Then I read through the jest webpack guide
4. Which led me to adding a "jest" property to my package.json
which mocks files and stylesheets:
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
}
5. Then I had to create the mocked files at the specified paths (you can use any path you want, those are just from their docs):
// __mocks__/styleMock.js
module.exports = {};
// __mocks__/fileMock.js
module.exports = 'test-file-stub';
Then it worked :)