如何使用 jest 进行 ESM 测试?

新手上路,请多包涵

我的设置

  • 节点 v14.16.0
  • 我有一个测试文件,其中包含一个用 ESM 模块编写的简单测试 ( import )。
  • package.json 我有一个脚本(遵循适用于 Windows 的 Jest 文档): "test": "set \"NODE_OPTIONS=--experimental-vm-modules\" && npx jest"
  • 我的测试运行 w/ npm run test (上面的脚本)

我的目标: 使用 jest 运行 ESM 测试。

我的尝试:

(1) CommonJS App w/ .js 测试

  • package.json 包含 "type": "commonjs"
  • 名为 test.js 测试文件
  • 错误: SyntaxError: Cannot use import statement outside a module (这是预期的,因为测试作为 commonjs 文件运行。)

(2) CommonJS App w/ .mjs 测试

  • package.json 包含 "type": "commonjs"
  • 测试文件名为 test.mjs
  • 错误: No tests found (Jest 没有找到文件?)

(3) ESM 应用 w/ .js 或 .mjs

  • package.json 现在有 "type": "module"
  • 名为 test.mjstest.js 的测试文件
  • 错误: ReferenceError: module is not defined at ...jest.config.js:6:1

(4) CommonJS App与CommonJS测试

  • package.json 包含 "type": "commonjs"
  • 测试文件名为 test.js 但使用 commonjs require 语法(并且没有我想包含的 ESM 模块);请注意, 这不是我想要 的,但包括在内只是为了表明测试本身没有任何问题。
  • 测试运行良好并通过

原文由 Luke 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 729
1 个回答

以下是我使用 ESM 通过测试运行 Jest 所采取的步骤。测试中的源文件也是使用 ESM 编写的。

  1. 将我的节点版本设置为 14.16.0

  2. 安装笑话:

    npm i jest -D

  1. 添加 "type": "module"package.json

  2. 更新 test package.json 的脚本:

    "scripts": {
     "test": "node --experimental-vm-modules ./node_modules/.bin/jest"
   }

  1. 使用以下内容创建一个 jest.config.js 文件:
    export default { transform: {} }

  1. 至少有一个可以使用默认值找到的测试 testMatch (我的在里面 __tests__ 目录)

  2. 运行测试:

    npm test

GitHub 上的 magic-comments-loader 存储库中有一个更完整的示例。

原文由 morganney 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题