我有一個獲取請求,但我從來沒有能夠在不克隆回應的情況下從回應中決議 json:response.clone().json()對于背景關系:
fetch(url) {
.then((response) => {
response.clone().json()
})
.((json) => {
//updates a state from `useState`
setResponse(json)
})
我對使用 Jest 和 testing-library 進行測驗是 100% 的新手,但到目前為止,我已經為 fetch 函式設定了一個模擬:
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我很好奇是否有另一種方法可以在不克隆的情況下獲取這些資料。
uj5u.com熱心網友回復:
您是正確的,您需要模擬所有子功能,也需要克隆。
但是您也正確,您不需要從 fetch 中克隆資料。您的語法似乎有點偏離,并且您沒有從函式中回傳 json。
試試這個
fetch(url)
.then((response) => response.json())
.then((json) => {
//updates a state from `useState`
setResponse(json);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416275.html
標籤:
上一篇:開玩笑地解決回圈依賴
