ECMAScript Modules

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

    The implementation may have bugs and lack features. For the latest status check out the issue and the on the issue tracker.

    Also note that the APIs Jest uses to implement ESM support are still considered experimental by Node (as of version ).

    With the warnings out of the way, this is how you activate ESM support in your tests.

    1. Ensure you either disable by passing transform: {} or otherwise configure your transformer to emit ESM rather than the default CommonJS (CJS).

    2. Beyond that, we attempt to follow node‘s logic for activating “ESM mode” (such as looking at in package.json or .mjs files), see their docs for details.

    Most 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 . To access this object in ESM, you need to import it from the @jest/globals module. To access this object in ESM, you need to import it from the @jest/globals module or use import.meta.

    Module mocking in ESM

    ESM mocking is supported through jest.unstable_mockModule. As the name suggests, this API is still work in progress, please follow for updates.

    The usage of jest.unstable_mockModule is essentially the same as jest.mock with two differences: the factory function is required and it can be sync or async:

    For mocking CJS modules, you should continue to use . See the example below:

    main.cjs

    main.test.cjs