[英]Jest mock for clone function
我有一個獲取請求,但我從來沒有能夠在不克隆響應的情況下從響應中解析 json: response.clone().json()
用於上下文:
fetch(url) {
.then((response) => {
response.clone().json()
})
.((json) => {
//updates a state from `useState`
setResponse(json)
})
我對使用 Jest 和測試庫進行測試是 100% 的新手,但到目前為止,我已經為 fetch function 設置了一個模擬:
useEffect(() => {
const mockedData = jest.fn(() => [{test: "title"}]);
global.fetch = jest.fn().mockResolvedValue((mockedData) =>
Promise.resolve({
json: () => Promise.resolve(JSON.stringify(mockedData))
})
)
}, []);
測試失敗說: error fetching response: TypeError: response.clone is not a function
。
如果我刪除global.fetch
的模擬,我會得到: ReferenceError: fetch is not defined
。 所以看來我需要模擬所有這些功能?
由於不知道如何通過clone
解決該問題,我很好奇是否有另一種方法可以在不克隆的情況下獲取這些數據。
您是正確的,您需要模擬所有子功能,也需要克隆。
但是您也正確,您不需要從 fetch 中克隆數據。 您的語法似乎有點偏離,並且您沒有從 function 返回 json。
嘗試這個
fetch(url)
.then((response) => response.json())
.then((json) => {
//updates a state from `useState`
setResponse(json);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.