Модули ECMAScript
Jest обеспечивает экспериментальную поддержку модулей ECMAScript (ESM).
Обратите внимание, что в текущей реализации существует множество ошибок, как известных, так и неизвестных. Кроме того, не весь функционал до конца реализован. 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/jest/bin/jest.js
orNODE_OPTIONS=--experimental-vm-modules npx jest
etc..В Windows вы можете использовать
cross-env
для настройки переменных среды.If you use Yarn, you can use
yarn node --experimental-vm-modules $(yarn bin jest)
. This command will also work if you use Yarn Plug'n'Play.Beyond that, we attempt to follow
node
's logic for activating "ESM mode" (such as looking attype
inpackage.json
or.mjs
files), see their docs for details.If you want to treat other file extensions (such as
.jsx
or.ts
) as ESM, please use theextensionsToTreatAsEsm
option.
Различия между ESM и CommonJS
Большинство различий объясняются в документации Node, но в дополнение к упомянутым в ней вещам, Jest добавляет специальную переменную во все исполняемые файлы - объект jest
. To access this object in ESM, you need to import it from the @jest/globals
module or use import.meta
.
import {jest} from '@jest/globals';
jest.useFakeTimers();
// etc.
// alternatively
import.meta.jest.useFakeTimers();
// jest === import.meta.jest => true
Пожалуйста, обратите внимание, что в настоящее время мы не поддерживаем jest.mock
в ESM, но мы намерены добавить это в будущем. Смотрите эту проблему для получения свежей информации.