Here are some different ways on how to set up Jest to support ESM. This applies for Jest v25, Node v13, and Babel v7.
Node v14 and Jest v26 support ESM natively with the --experimental-vm-modules
flag.
Install cross-env
:
yarn add --dev cross-env
Add NODE_OPTIONS
to the scripts.test in package.json:
"scripts": {
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
}
See tne Jest documentation for more info: https://jestjs.io/docs/ecmascript-modules
Add babel-jest
.
yarn add --dev @babel/core @babel/plugin-transform-modules-commonjs babel-jest
Configure Babel. We'll use env.test here so not to interfere with your build process.
// babel.config.js
module.exports = {
env: {
test: {
plugins: ["@babel/plugin-transform-modules-commonjs"]
}
}
};
Configure Jest:
// jest.config.js
module.exports = {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
};
You're done.
Add jest-esm-transformer
- this is a preset configuration of Babel to support ESM transpilation.
yarn add --dev jest-esm-transformer
Configure Jest.
// jest.config.js
module.exports = {
"transform": {
"\\.m?jsx?$": "jest-esm-transformer"
},
};
You're done.
As of March 2020, using esm
is currently not possible. Follow these threads for details.
See buble-jest
.
Method C : kind of working for me but there are cases like optional changing it is still not able to recognize it, in the mean time did anyone had a work around for this.
the case scenario is like I had utility function in react JavaScript file which in turn using lodash function and I am trying to use this utility functions in automation test cases using jest, its stucked to optional chaining part and some other parts as well.
do anyone of you here can recommend something better