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 type in package.json or .mjs files), see their docs for details.

    Module mocking in ESM

    Since ESM evaluates static import statements before looking at the code, the hoisting of jest.mock calls that happens in CJS won’t work for ESM. To mock modules in ESM, you need to use require or dynamic import() after jest.mock calls to load the mocked modules - the same applies to modules which load the mocked modules.

    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