My setup
import
).package.json
I have a script (following Jest documentation adapted to Windows): "test": "set \"NODE_OPTIONS=--experimental-vm-modules\" && npx jest"
npm run test
(the script above)My goal: Run the ESM tests using jest.
My attempts:
package.json
contains "type": "commonjs"
test.js
SyntaxError: Cannot use import statement outside a module
(This is expected because the test is being run as a commonjs file.)package.json
contains "type": "commonjs"
test.mjs
No tests found
(Jest isn't finding the file?)package.json
now has "type": "module"
test.mjs
or test.js
ReferenceError: module is not defined at ...jest.config.js:6:1
package.json
contains "type": "commonjs"
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.Here are the steps I took to run Jest with a test using ESM. The source files under test were also written using ESM.
npm i jest -D
installs Jest as a dev dependency"type": "module"
to package.json
scripts
in package.json
to include "test": "node --experimental-vm-modules ./node_modules/.bin/jest"
jest.config.js
file with the following content: export default { transform: {} }
testMatch
(mine was inside __tests__
dir)npm test
There is a more complete example in the webpack-strip-debug-loader repository on GitHub.
After a lot of fiddling, this is my successful setup (the parts that matter):
package.json
has "type": "commonjs",
"script": {
"test": "NODE_OPTIONS=--experimental-vm-modules jest"
}
jest.config.mjs
(yes, esModule)export default {
moduleFileExtensions: [
"mjs",
// must include "js" to pass validation https://github.com/facebook/jest/issues/12116
"js",
],
testRegex: `test\.mjs$`,
};
That having to include "js"
is a historic relic from the times modules where obviously .js files. Follow https://github.com/facebook/jest/issues/12116 for update.
For me to work it was only necessarry to set script "test" as follows:
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules npx jest"
and yeah, don't forget -> npm i cross-env jest