Skip to main content
Versão: 26.x

Módulos ECMAScript

atenção

Jest vem com suporte experimental para Módulos ECMAScript (ESM).

A implementação pode haver bugs e falta de recursos. For the latest status check out the issue and the label on the issue tracker.

Também note que, as APIs que o Jest usa para implementar o suporte ESM ainda são consideradas experimentais pelo Node (como da versão 18.8.0).

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

  1. Certifique-se de desativar code transforms passando transform: {} ou configurando seu transformador para emitir ESM em vez do CommonJS padrão (CJS).

  2. Execute node with --experimental-vm-modules, e.g. node --experimental-vm-modules node_modules/jest/bin/jest.js or NODE_OPTIONS=--experimental-vm-modules npx jest etc.

    No Windows, você pode utilizar cross-env, para definir as variáveis de ambiente.

    Se você utiliza o Yarn, poderá usar yarn node --experimental-vm-modules $(yarn bin jest). This command will also work if you use Yarn Plug'n'Play.

  3. 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.

Diferenças entre ESM e CommonJS

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

import {jest} from '@jest/globals';

jest.useFakeTimers();

// etc.

Additionally, since ESM evaluates static import statements before looking at the code, the hoisting of jest.mock calls that happens in CJS won't work in 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.

main.cjs
const {BrowserWindow, app} = require('electron');

// etc.

module.exports = {example};
main.test.cjs
import {createRequire} from 'node:module';
import {jest} from '@jest/globals';

const require = createRequire(import.meta.url);

jest.mock('electron', () => ({
app: {
on: jest.fn(),
whenReady: jest.fn(() => Promise.resolve()),
},
BrowserWindow: jest.fn().mockImplementation(() => ({
// partial mocks.
})),
}));

const {BrowserWindow} = require('electron');
const exported = require('./main.cjs');

// alternatively
const {BrowserWindow} = (await import('electron')).default;
const exported = await import('./main.cjs');

// etc.

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.