In this post we're going to see two possible ways of enabling ES6 Modules with Jest that works with all operating systems.
So, following is the screenshot of the file structure, nothing complex just a simple node app with jest installed (npm i jest)
And following is the contents of index.js and index.test.js.
index.js
export default (a, b) => a + b;
index.test.js
import sum from "./index.js";
it("should sum", () => {
expect(sum(1, 2)).toBe(3);
});
Now, let's update the test script and enable ES6 modules in package.json.
package.json
{
"name": "jest-es6-modules",
"type": "module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"jest": "^27.0.6"
}
}
But if you run npm test you would notice Jest is complaining that it cannot recognize import, so let's fix this.
Method 1
All you need to do is set the experimental-vm-modules flag. Just modify the test script in package.json to the following:
package.json
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
}
Method 2
You can also install cross-env as a dev dependency and use that for setting NODE_OPTIONS.
npm i --save-dev cross-env
package.json
"scripts": {
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
}
Now, you can use ES6 modules with Jest. Hurray!


Top comments (0)