我的设置
import
)。package.json
中,我有一个脚本(遵循适用于Windows的Jest文档):"test": "set \"NODE_OPTIONS=--experimental-vm-modules\" && npx jest"
npm run test
(上面的脚本)运行的我的目标: 使用 jest 运行 ESM 测试。
我的尝试:
package.json
包含 "type": "commonjs"
test.js
SyntaxError: Cannot use import statement outside a module
(这是预期的,因为测试是作为 commonjs 文件运行的。)package.json
包含 "type": "commonjs"
test.mjs
No tests found
(Jest 找不到该文件?)package.json
现在有"type": "module"
test.mjs
或 test.js
ReferenceError: module is not defined at ...jest.config.js:6:1
package.json
包含 "type": "commonjs"
test.js
的测试文件,但使用 commonjs require
语法(并且没有我想包含的 ESM 模块);请注意,这不是我想要的,但包含在内只是为了表明测试本身没有任何问题。以下是我使用 ESM 运行 Jest 并进行测试所采取的步骤。测试的源文件也是使用ESM编写的。
将我的节点版本设置为14.16.0
安装 Jest:
npm i jest -D
将
"type": "module"
添加到 package.json
更新
test
中的package.json
脚本:
"scripts": {
"test": "node --experimental-vm-modules ./node_modules/.bin/jest"
}
创建一个包含以下内容的
jest.config.js
文件:
export default { transform: {} }
testMatch
(我的在__tests__
目录中)
运行测试:
npm test
GitHub 上的magic-comments-loader 存储库中有一个更完整的示例。
为了我的工作,只需要设置脚本“测试”如下:
“测试”:“跨环境 NODE_OPTIONS=--experimental-vm-modules npx 玩笑”
是的,别忘了 ->
npm i cross-env jest
经过大量摆弄,这是我成功的设置(重要的部分):
package.json
有 "type": "commonjs",
"script": {
"test": "NODE_OPTIONS=--experimental-vm-modules jest"
}
jest.config.mjs
(是的,esModule)export default {
moduleFileExtensions: [
"mjs",
// must include "js" to pass validation https://github.com/facebook/jest/issues/12116
"js",
],
testRegex: `test\.mjs$`,
};
必须包含
"js"
是时代模块中的历史遗迹,其中显然是 .js 文件。关注https://github.com/facebook/jest/issues/12116获取更新。
这是您需要的最低限度。支持@Luke 上面的评论以及我需要的 testMatch 答案。
package.json
- 确保 "type": "module"
在那里
jest.config.js
- 将此 glob 添加到您的 testMatch
数组中:"**/?(*.)+(spec|test).(m)js"
确保您的测试文件以
.spec.mjs
或 .test.mjs
结尾以匹配 glob
将
npm test
脚本设置为 node --experimental-vm-modules ./node_modules/.bin/jest
就是这样。您不需要笑话配置中的转换设置,如文档所示。
就我而言,离开
"type": "module"
并重命名
jest.config.js
至 jest.config.cjs
babel.config.js
至 babel.config.cjs
工作了
我遵循了@morganney的答案,但我收到了这个错误:
"basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")..."
。所以为了让它工作,我使用了该属性
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
来自 文档。
因此我的 package.json 最终配置如下:
{
"type": "module",
"jest": {
"transform": {}
},
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
}
"dependencies": {
"jsdom": "^17.0.0",
}
}
esm
npm 包
npm i --save-dev esm
在没有任何额外的笑话配置的情况下为我解决了这个问题。因为 ESM 包有一个
require
功能,可以替代 CJS require。因此,您将在每个测试 ESM 的 jest 文件中使用 ESM 覆盖 CJS require 函数。
因此,例如要测试
yourESModule.js
(这是一个带有玩笑的 ESM),您可以使用以下内容开始 yourESModule.test.js
:
require = require('esm')(module)
const { yourFunction } = require('./yourESModule')
顺便说一句,我的笑话版本是
"jest": "^29.6.1"
然后运行:
npx jest
希望这有帮助!