Run Jest on Native ES Modules


Here's how to run your tests on ES modules without compiling.

Mark Project as an ES Module

To be a real ES module, you really have to want it. More than Pinnochio. Don't get distracted by Pleasure Island. Get to work. Save your father.

And on your way, edit your package.json to show that you are a real ES module:

{
  "type": "module"
}

Write Source

Something simple will do in index.js:

export function add(a, b) {
  return a + b
}

See, native ESM. We're exporting. It's a .js file.

Write Test

Again, we're just testing.

import { add } from './index.js'

test('works', () => {
  expect(add(1, 2)).toEqual(3)
})

Native ES module import.

Install Jest

npm install jest

Now you have a test runner.

Run the Test

For some reason this still requires an experimental flag (even tested on nodejs@20.2.0 this morning).

Modify your package.json again so you don't have to type this every time:

{
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
  }
}

Run it, and see the output:

> npm test

 PASS  src/index.test.js
  ✓ works (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.238 s
Ran all test suites.
``

Just JavaScript. Just ESM. No compile. Fast, simple, tested.