Does Jest support ES6 import/export?
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
.
For an updated configuration, I'm using https://babeljs.io/setup#installation
Select JEST and be happy:
As a reference, the current configuration:
npm install --save-dev babel-jest
In your package.json file, make the following changes:
{
"scripts": {
"test": "jest"
},
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
}
Install babel preset:
npm install @babel/preset-env --save-dev
Create a .babelrc
file:
{
"presets": ["@babel/preset-env"]
}
Run your tests:
npm run test
UPDATE 2020 - native support of ECMAScript modules (ESM)
According to this issue, there is native support of ESM from [email protected]
. 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:
- Make sure you don't transform away
import
statements by settingtransform: {}
in config file - Run
node@^12.16.0 || >=13.2.0
with--experimental-vm-modules
flag - Run your test with
jest-environment-node
orjest-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
Also note in the Github issue that this approach does not yet support the jest
object. So you may need to import it manually:
import {jest} from '@jest/globals'
(I hope this will change in the future)