[英]How to use ESM tests with jest?
我的設置
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
更新package.json
中的test
腳本:
"scripts": { "test": "node --experimental-vm-modules ./node_modules/.bin/jest" }
創建一個包含以下內容的jest.config.js
文件:
export default { transform: {} }
至少有一個可以使用默認testMatch
找到的測試(我的在__tests__
目錄中)
運行測試:
npm test
GitHub 上的webpack-strip-debug-loader存儲庫中有一個更完整的示例。
對我來說,只需將腳本“測試”設置如下:
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules npx jest"
是的,別忘了 -> 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
而已。 正如文檔所建議的那樣,您不需要在 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",
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.