Jest and ESM throwing errors with import fs

Viewed 29

I am converting a node package into pure ESM. I have done the import changes to my files, added "type":"module" to package.json and also used "exports":"./lib/index.js"

When I run the test, I get the this common error:

    /x/__tests__/values.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import fs from 'fs'
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

I've looked only, through many examples and Q&A, but almost all of them refers to changes with ts-node or babel. My package is quite simple, it does not use babel and it's plain javascript.

I am getting a bit stuck here, because I am nearly sure it's not a bug, but also I can't fix it.

I do not have any transform or transformIgnorePatterns. The test import section is

import fs from 'fs'
import { values } from "../lib/index.js"

const expectedData = JSON.parse(fs.readFileSync(__dirname + "/testfiles/values.output.json"))

Jest is version 29.0.1

Node is version 16.17.0

1 Answers

Jest does not understand ESM syntax out of the box.

Jest ships with experimental support for ECMAScript Modules (ESM).

It is experimental and has many bugs.

You need to transpile your ESM syntax to CJS when running tests.

Babel is one option

  1. Create .babelrc file with the following content
{
  "env": {
    "test": {
      "plugins": ["@babel/plugin-transform-modules-commonjs"]
    }
  }
}
  1. Install the plugin
npm i -D @babel/plugin-transform-modules-commonjs

And that's it, now you can use ESM syntax in your tests.

If you want something else you can check the official docs

Related