我的设置
import
)编写的简单测试。package.json
中,我有一个脚本(下面是适应开玩笑的文件的脚本):"test": "set \"NODE_OPTIONS=--experimental-vm-modules\" && npx jest"
npm run test
(上面的脚本)我的目标:使用jest运行ESM测试。
My的尝试:
(1) CommonJS App / .js测试
package.json
包含"type": "commonjs"
test.js
的测试文件SyntaxError: Cannot use import statement outside a module
(这是因为测试是作为一个公共文件运行的)。(2) CommonJS App / .mjs测试
package.json
包含"type": "commonjs"
test.mjs
的测试文件No tests found
(Jest没有找到文件?)(3) ESM应用程序w/ .js或.mjs
package.json
现在有"type": "module"
test.mjs
或test.js
的测试文件ReferenceError: module is not defined at ...jest.config.js:6:1
(4) CommonJS应用程序与CommonJS测试
package.json
包含"type": "commonjs"
test.js
的测试文件,但使用了通用的require
语法(没有ESM模块,我想要包含);请注意,这不是我想要的,但是包含它只是为了表明测试本身没有什么问题。发布于 2021-09-05 00:25:37
下面是我使用ESM运行Jest测试时所采取的步骤。测试中的源文件也是用ESM编写的。
"type": "module"
添加到package.json
test
中更新package.json
脚本:
“脚本”:{“测试”:“节点-实验-vm-模块./节点_模块/..bin/jest”}jest.config.js
文件:
导出默认{ transform:{} }testMatch
找到的测试(我的测试在__tests__
dir中)在魔术-注释-加载程序存储库中有一个关于GitHub的更完整的示例。
发布于 2021-12-06 07:33:14
经过大量的修改后,这是我成功的设置(重要的部分):
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进行更新。
发布于 2022-05-20 20:53:28
这是你需要的最低限度。道具@路克上面的评论与我需要的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
就这样。您的不需要-- jest配置中的转换设置为文件显示。
https://stackoverflow.com/questions/68956636
复制相似问题