DEV Community

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Posted on

Using ES6 Modules with Jest

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)

image

And following is the contents of index.js and index.test.js.

index.js

export default (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

index.test.js

import sum from "./index.js";

it("should sum", () => {
  expect(sum(1, 2)).toBe(3);
});
Enter fullscreen mode Exit fullscreen mode

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"
  }
}
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

package.json

"scripts": {
  "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
}
Enter fullscreen mode Exit fullscreen mode

Now, you can use ES6 modules with Jest. Hurray!

image

Discussion (0)