Is it possible to test ES6 Modules with Jest without esm
or babel
? Since node v13
supports es6 natively have tried:
//package.json { … "type": "module" … } //__tests__/a.js import Foo from '../src/Foo.js'; $ npx jest Jest encountered an unexpected token … Details: /home/node/xxx/__tests__/a.js:1 import Foo from '../src/Foo.js'; ^^^^^^ SyntaxError: Cannot use import statement outside a module
When babel is added a transpiler, it works, but can es6 modules be used natively as well?
Jest ships with experimental support for ECMAScript Modules (ESM). Note that due to its experimental nature there are many bugs and missing features in Jest's implementation, both known and unknown. You should check out the tracking issue and the label on the issue tracker for the latest status.
In May, 2020, Node. js v12. 17.0 made ESM support available to all Node. js applications (without experimental flags).
It's finally happened: nearly 4 years after the import keyword was introduced in ES6, Node. js introduced experimental support for ES6 imports and exports. In Node. js 12, you can use import and export in your project if you do both of the below items.
Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error.
Yes, it is possible from [email protected]
. From this version, there is a native support of esm, so you will not have to transpile your code with babel anymore.
It is not documented yet, but according to this issue you have to do 3 easy steps to achieve that (At the time of writing this answer):
import
statements by setting transform: {}
in your jest config filenode@^12.16.0 || >=13.2.0
with --experimental-vm-modules
flagjest-environment-node
or jest-environment-jsdom-sixteen
.So your jest config file should contain at least this:
export default { testEnvironment: 'jest-environment-node', transform: {} ... };
And to set --experimental-vm-modules
flag, you will have to run Jest from package.json
as follows (I hope this will change in the future):
"scripts": { "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js" }
I hope, this answer was helpful to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With