javascript - 使用 ES6 导入语句节点运行测试
问题描述
我在 ubuntu 上使用 nodev15.0.1
和 jest 。26.6.0
18.04.5
我已经设置了一个简单的测试用例,并在文件顶部尝试使用 ES6 导入语句:
import Color from './color.js'
test("Initialized properly after construction", () => {
expect(1 + 1).toBe(2);
});
此外,这里是 color.js 的代码:
class Color {
constructor(r, g, b, a) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
}
export {
Color
};
当我运行 jest 时,我得到以下错误输出:
FAIL src/modules/color.test.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/home/daniel/Documents/raycaster/src/modules/color.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Color from './color.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at new Script (node:vm:100:7)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.288 s
Ran all test suites.
npm ERR! code 1
基于 Jest 文档https://jestjs.io/docs/en/ecmascript-modules,我已将以下内容添加到我的package.json
文件中:
"type": "module",
"jest": {
"testEnvironment": "jest-environment-node",
"transform": {}
}
尽管有这些配置,但 jest 似乎无法在 ES6 兼容模式下运行。我需要做哪些配置才能启用导入语句?
解决方案
我找到了Node v13 / Jest / ES6 — 对没有 babel 或 esm 的模块的原生支持
其中突出显示了我需要的部分:
在我的package.json
文件中,我需要指定以下内容:
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
推荐阅读
- go - Golang:解释 DumpRequest 和 DumpResponse HTTP/2
- xpath - 其祖先具有包含特定文本字符串的后代的文本节点的 XPath
- python - 将连续数据从 python 脚本流式传输到 NodeJS
- c# - 实例化具有属性的类时的 C# 回调
- json - JSON Schema:如何检查每个具有特定值的数组项是否具有所需的属性?
- python - 提取元素文本
- sql - 如果它们是在一分钟内写入的,如何从表中删除重复的行?
- vulkan - Vulkan:在后续 RenderPass 中读取附件数据的方式
- postgresql - psql 创建用户 SUPER USER WITH 密码抛出语法错误消息
- java - 如何让我的应用在给定时间发送定期短信?