Thursday 2 September 2021

How to use ESM tests with jest?

My setup

  • Node v14.16.0
  • I have one test file that contains a simple test written with ESM modules (import).
  • In package.json I have a script (following Jest documentation adapted to Windows): "test": "set \"NODE_OPTIONS=--experimental-vm-modules\" && npx jest"
  • My tests are run w/ npm run test (the script above)

My goal: Run the ESM tests using jest.

My attempts:

(1) CommonJS App w/ .js test

  • package.json contains "type": "commonjs"
  • Test file named test.js
  • Error: SyntaxError: Cannot use import statement outside a module (This is expected because the test is being run as a commonjs file.)

(2) CommonJS App w/ .mjs test

  • package.json contains "type": "commonjs"
  • Test file named test.mjs
  • Error: No tests found (Jest isn't finding the file?)

(3) ESM App w/ .js or .mjs

  • package.json now has "type": "module"
  • Test file named test.mjs or test.js
  • Error: ReferenceError: module is not defined at ...jest.config.js:6:1

(4) CommonJS App and CommonJS test

  • package.json contains "type": "commonjs"
  • Test file named test.js but using the commonjs require syntax (and without the ESM modules I'd like to include); Note that this is not what I want, but included just to show there's nothing wrong with the test itself.
  • Test runs fine and passes


from How to use ESM tests with jest?

No comments:

Post a Comment