[英]'ReferenceError: jest is not defined' when running unit test
我正處於一個新應用程序的早期階段,到目前為止它只使用 vanilla JS。 我正在嘗試將 ES6 模塊用於我的 Jest 單元測試,因此我遵循了2020 年更新的說明來實現這一點。
但是,按照這些說明操作后,我收到錯誤ReferenceError: jest is not defined
when running my unit test。
這是我的 package.json:
{
"version": "1.0.0",
"main": "app.js",
"type": "module",
"jest": {
"testEnvironment": "jest-environment-node",
"transform": {}
},
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"start": "node server.js"
},
"license": "ISC",
"devDependencies": {
"express": "^4.17.1",
"jest": "^26.6.3",
"jest-environment-node": "^26.6.2",
"open": "^7.3.0"
},
"dependencies": {}
}
下面是我的測試文件。 由於 jest.fn 調用而發生錯誤:
import { getTotalNumPeople } from "./app.js";
test("Get total number of people", async () => {
global.fetch = jest.fn(() => Promise.resolve({
json: () => Promise.resolve({count: 15})
})
)
expect(await getTotalNumPeople()).toBe(15);
});
關於為什么會發生這種情況的任何想法? 我相信這個問題與我為支持 ES6 模塊所遵循的步驟有關。 在這些更改之前,當我簡單地將getTotalNumPeople
function 粘貼到我的測試文件中時,我的測試運行良好。
如果我注釋掉 mocking 我的 function,我就會得到一個關於未定義提取的 ReferenceError(因為getTotalNumPeople
使用提取)。 所以這不僅僅是沒有定義的jest
。
我注意到,如果我沒有指定jest-environment-node
作為我的測試環境,錯誤會更改為ReferenceError: global is not defined
由於在我的測試中引用了global.fetch
。 只是想我會注意到以防萬一。
看起來您沒有導入 jest,因此您只需將此行添加到文件頂部:
import {jest} from '@jest/globals'
有關更多詳細信息,請參閱有關 Jest 中對 ES6 模塊的本機支持的問題。
雖然與 Rupesh 的答案基本相同 - 您可以全局公開jest
而不必將其導入每個測試文件 - 通過將設置文件添加到 jest 配置:
"jest": {
"setupFiles": [
"<rootDir>/test-setup.js"
]
}
然后將其添加到test-setup.js
:
import { jest } from '@jest/globals';
global.jest = jest;
通常,package.json 中的test
腳本也改進了 ESM 對 jest 的支持,如下所示:
"scripts": {
"test": "node --no-warnings --experimental-vm-modules $( [ -f ./node_modules/.bin/jest ] && echo ./node_modules/.bin/jest || which jest )"
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.