ECMAScript Modules
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.
Also note that the APIs Jest uses to implement ESM support is still considered experimental by Node (as of version
14.13.1
).
With the warnings out of the way, this is how you activate ESM support in your tests.
- Ensure you either disable code transforms by passing
transform: {}
or otherwise configure your transformer to emit ESM rather than the default CommonJS (CJS). - Execute
node
with--experimental-vm-modules
, e.g.node --experimental-vm-modules node_modules/.bin/jest
orNODE_OPTIONS=--experimental-vm-modules npx jest
etc.. On Windows, you can usecross-env
to be able to set environment variables - Beyond that, we attempt to follow
node
's logic for activating "ESM mode" (such as looking attype
inpackage.json
ormjs
files), see their docs for details
#
Differences between ESM and CommonJSMost of the differences are explained in Node's documentation, but in addition to the things mentioned there, Jest injects a special variable into all executed files - the jest
object. To access this object in ESM, you need to import it from the @jest/globals
module.
Please note that we currently don't support jest.mock
in a clean way in ESM, but that is something we intend to add proper support for in the future. Follow this issue for updates.