Skip to main content

Testing ES modules with Jest

Here are a few troubleshooting tips to enable Jest, the JavaScript testing framework, to be able to work with ES modules without needing Babel in the mix for transpilation. Let’s get going with a basic set-up.

package.json

…,
"scripts": {
  "test": "NODE_ENV=test NODE_OPTIONS=--experimental-vm-modules jest"
},
"type": "module",
"devDependencies": {
  "jest": "^27.2.2"
}

Note: take note of the crucial "type": "module" part as it’s the least-documented bit and your most likely omission!

After that set-up, you’re free to import and export to your heart’s content.

javascript/sum.js

export const sum = (a, b) => {
  return a + b;
}

spec/sum.test.js

import { sum } from "../javascript/sum.js";
    
test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

Hopefully that’ll save you (and future me) some head-scratching.

(Reference: Jest’s EcmaScript Modules docs page)

External Link Bookmark Note Entry Search