如果我正在測驗一個進行 fetch 呼叫的函式,并且我在專案中擁有的所有 fetch 呼叫都只是為了在瀏覽器中運行。我是否仍然需要在節點上安裝一些包并匯入它才能模擬該 fetch 呼叫?
像這樣的簡單場景會引發ReferenceError: fetch is not defined
Jest 測驗:
// fetcKey.js
export async function fetchKey() {
try {
const key = await fetch('http://localhost:3000/key');
return (await key.text());
}
catch(error){
throw error;
}
}
//fetchKey.test.js
import fetchKey from './fetchKey'
test('Checks fetchKey return', () => {
expect(fetchKey()).not.toThrow();
})
uj5u.com熱心網友回復:
您應該能夠使用node-fetch
:
import fetch from 'node-fetch';
(請注意,它是一個 ECMAScript 模塊,不能使用 匯入require
,如他們的檔案中所述)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489642.html
標籤:javascript 节点.js 测试 开玩笑的 拿来
上一篇:沒有URL的自動化測驗