Перейти до основного змісту
Версія: 25.x

Модулі ECMAScript

caution

Jest експериментально підтримує ECMAScript Модулі (ESM).

В реалізації можуть бути помилки та нестача функцій. For the latest status check out the issue and the label on the issue tracker.

Також варто пам'ятати, що API, які Jest використовує для реалізації підтримки ESM, все ще вважаються експериментальними для Node (на момент версії 18.8.0).

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

  1. Переконайтесь, що ви вимкнули перетворення коду, передавши transform: {}, або будь-яким іншим чином налаштували перетворювач для використання ESM замість CommonJS (CJS) за замовчуванням.

  2. Виконайте node з --experimental-vm-modules, наприклад, node --experimental-vm-modules node_modules/jest/bin/jest.js або NODE_OPTIONS=--experimental-vm-modules npx jest і так далі.

    На Windows, ви можете використовувати cross-env для налаштування змінних середовища.

    Якщо ви користуєтесь Yarn, ви можете використовувати yarn node --experimental-vm-modules $(yarn bin jest). Ця команда працює й для 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.

Відмінності між ESM і 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');

// і так далі

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(() => ({
// часткові імітації.
})),
}));

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

// інший варіант
const {BrowserWindow} = (await import('electron')).default;
const exported = await import('./main.cjs');

// і так далі

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.