[英]Running tests with ES6 import statements node
我使用節點v15.0.1
,並開玩笑26.6.0
在Ubuntu 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 兼容模式下運行。 我需要做哪些配置才能啟用導入語句?
由於您將類作為默認導出導入,因此您需要一個默認值。 有關更多見解,請查看https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
class Color {
constructor(r, g, b, a) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
}
export default Color;
正如參考文獻所述,
babel-jest 在安裝 Jest 時會自動安裝,如果你的項目中存在 babel 配置,它會自動轉換文件。 為避免這種行為,您可以顯式重置轉換配置選項:
<...>
轉變: {},
這正是這個配置所做的,它禁用了 Babel 並防止import
被轉譯。
解決方案是刪除transform: {}
並僅故意使用transform
。
提到的參考部分專用於 Node.js 中的原生 ES 模塊支持。 它表明transform: {}
需要通過以下方式啟用它們:
node --experimental-vm-modules node_modules/.bin/jest
不建議經常使用,因為 Node 和 Jest 中的 ESM 支持是實驗性的,可能會導致問題和缺乏功能,因為 Jest 已經嚴重依賴於 CommonJS 模塊。
我發現Node v13 / Jest / ES6 — 對沒有 babel 或 esm 的模塊的原生支持
其中突出顯示了我需要的部分:
在我的package.json
文件中,我需要指定以下內容:
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.