【发布时间】:2021-02-05 23:47:40
【问题描述】:
我在 ubuntu 18.04.5 上使用节点 v15.0.1 和 jest 26.6.0。
我已经设置了一个简单的测试用例,并且在文件的顶部我尝试使用 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 兼容模式下运行。我需要做哪些配置才能启用导入语句?
【问题讨论】:
-
欢迎分享color.js的内容
-
@chyke007 已经添加了 color.js 的内容
标签: javascript node.js jestjs es6-modules