Jest + JavaScript ES Modules

27 views Asked by At

I've built a command-line tool in JavaScript. I want to write tests for it. I thought of Jest as the first option.

I'm getting the following error when running the tests: SyntaxError: Cannot use import statement outside a module.

Here's what I've tried:

  • I've installed Jest and its dependencies via npm install --save-dev jest @babel/core @babel/preset-env babel-jest
  • I created a babel.config.cjs file with the following content:
module.exports = {
  presets: [["@babel/preset-env", { targets: { node: "current" } }]],
};

  • I've updated the following sections in my package.json:
  "type": "module",
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\\.js$": "babel-jest"
    }
  },
  • My tests are inside of a __tests__ folder, and the test files have the following naming convention fileName.test.js
1

There are 1 answers

0
Guillaume Brunerie On

You need to enable experimental support for ES modules. Try the following in your package.json, instead of simply jest:

NODE_OPTIONS='--experimental-vm-modules' jest