`regeneratorRuntime` is not defined when running Jest test
In case you are using a setupTests.js file you can import regenerator-runtime from there:
// setupTests.js
import 'regenerator-runtime/runtime'
import Enzyme from 'enzyme'
import EnzymeAdapter from 'enzyme-adapter-react-16'
Enzyme.configure({
adapter: new EnzymeAdapter()
})
Then you can import setupTests.js to every test file or better yet, in your package.json just add setupFilesAfterEnv to the jest config:
// package.json
{
...
"dependencies": {
...
},
"devDependencies": {
...
},
"jest": {
"setupFilesAfterEnv": ["./pathToYour/setupTests.js"]
}
}
Don't forget to install the regenerator-runtime package:
$ yarn add regenerator-runtime --dev
There is no need to import the complete babel-polyfill (or @babel/polyfill if Babel ≥ v.7.0.0) that btw has been deprecated in favor of directly including core-js/stable and regenerator-runtime/runtime.
While importing babel-polyfill
into each test worked, the Updated jest docs (v24) suggests setting this in your babel config. If you do this you should no longer need to import babel-polyfill
. (Personally, I was missing the targets
option from my preset-env
config).
// babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
A word to the wise: specifying targets
will override any browserslist
config you have defined (that babel would otherwise use). So in a web project, you'll probably want to create a dynamic babel.config.js
that is "jest-aware" so that you're only adding targets
when it's a test environment. See the section titled "Making your Babel config jest-aware" in the jest docs.