TLDR: How can I configure jest
so that it uses babel
to compile the test files and the files required in globalSetup
and globalTeardown
?
I've been struggling a lot to configure jest
and babel
. It seems that when I run my tests babel
fails to load the configuration file, or perhaps it doesn't run at all.
in package.json:
{
"scripts": {
"start": "babel-node src/index.js",
"test": "jest src/tests/*.test.js",
},
"devDependencies": {
"@babel/cli": "^7.0.0-rc.1",
"@babel/core": "^7.0.0-rc.1",
"@babel/node": "^7.0.0-rc.1",
"@babel/preset-env": "^7.0.0-rc.1",
"babel-jest": "^23.4.2",
"jest": "^23.5.0",
}
}
in babel.config.js:
module.exports = (api) => {
if (api) api.cache(true);
const presets = ['@babel/preset-env'];
const plugins = [];
return {
presets,
plugins,
};
};
in jest.config.js:
module.exports = {
globalSetup: './src/config/jest/setup',
globalTeardown: './src/config/jest/teardown',
};
When I run npm run test
I get the following error:
import app from '../../index';
^^^^^^ SyntaxError: Unexpected token import
...which I assume means that babel
failed to configure properly. I tried logging on both config files and babel.config.js
is only run when I do npm start
.
When I used an identical configuration with .babelrc
instead, the tests could run. However the globalSetup
and globalTeardown
could not.
Jest currently doesn't transform modules defined in globalSetup
and globalTeardown
. There's an open GitHub discussion here.
That being said, there are some workarounds on the same thread. You'll have to require babel-register
and babel-polyfill
on top of your jest.config.js
. Here is the full implementation: https://github.com/facebook/jest/issues/5164#issuecomment-366139663
If someone is using TypeScript requiring ts-node/register
should make it work. https://github.com/facebook/jest/issues/5164#issuecomment-376006851
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With