If I use import/export
from ES6 then all my Jest tests fail with error:
Unexpected reserved word
I convert my object un
In addition to installing babel-jest
(which comes with Jest by default now) be sure to install regenerator-runtime
.
According to this issue, there is native support of ESM from jest@25.4.0
. So you won't have to use babel anymore. At the time of writing this answer (05/2020), to activate that you need to do three simple things:
import
statements by setting transform: {}
in config filenode@^12.16.0 || >=13.2.0
with --experimental-vm-modules
flagjest-environment-node
or jest-environment-jsdom-sixteen
.So your Jest configuration file should contain at least this:
export default {
testEnvironment: 'jest-environment-node',
transform: {}
...
};
And to set --experimental-vm-modules
flag, you will have to run Jest as follows:
node --experimental-vm-modules node_modules/jest/bin/jest.js
(I hope this will change in the future)
I encountered the same issue.
These are what I did:
yarn add --dev babel-jest @babel/core @babel/preset-env
Make file jest.config.js in rootDir.
module.exports = {
moduleFileExtensions: ["js", "json", "jsx", "ts", "tsx", "json"],
transform: {
'^.+\\.(js|jsx)?$': 'babel-jest'
},
testEnvironment: 'node',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1'
},
testMatch: [
'<rootDir>/**/*.test.(js|jsx|ts|tsx)', '<rootDir>/(tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
],
transformIgnorePatterns: ['<rootDir>/node_modules/']
};
Then make file babal.config.js in rootDir.
Go like this:
module.exports = {
"presets": ["@babel/preset-env"]
}
From my answer to another question, this can be simpler:
The only requirement is to configure your test
environment to Babel, and add the ECMAScript 6 transform plugin:
Step 1:
Add your test
environment to .babelrc
in the root of your project:
{
"env": {
"test": {
"plugins": ["@babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the ECMAScript 6 transform plugin:
npm install --save-dev @babel/plugin-transform-modules-commonjs
And that's it. Jest will enable compilation from ECMAScript modules to CommonJS automatically, without having to inform additional options to your jest
property inside package.json
.
It's a matter of adding stage-0 to your .babelrc file. Here is an example:
{
"presets": ["es2015", "react", "stage-0"],
"plugins": ["transform-decorators-legacy"]
}
I solved it with .default
.
Try
var Validation = require('../src/components/validation/validation').default;