[英]Jest Mock not returning the mock data while writing Unit Test in react
我正在使用 fetch 調用 API 並為此編寫測試用例。 在進行 Fetch 調用時,我期望得到模擬數據但收到 API 錯誤消息。
請幫助我知道為什么它不嘲笑數據。
使用 Jest、jest-fetch-mock 模塊。 代碼如下
const login = (username, password) => {
return fetch('endpoint/login', () => {
method: 'POST',
body: JSON.stringify({
data :{
username,
password
}
})
})
.then (res => res.json())
.then (data => {
if(data.response){
return {
response: "accessToken",
error: null
}
}else{
return {
response: null,
error: "Something went wrong"
}
}
})
}
現在我正在編寫單元測試來測試這個 api,如下:-
test("Auth Success Scenario", async () => {
const onResponse = jest.fn();
const onError = jest.fn();
fetchMock.mockResponseONce(JSON.stringify({
data: {
response: "accessToken",
error: null
}
}));
return await AuthService.login("andy","password")
.then(onResponse)
.catch(onError)
.finally( () => {
console.log(onResponse.mock.calls[0][0]) // its return API error not mocked data
})
})
這是評論,遺憾的是我沒有足夠的聲譽。
您是否啟用了文檔鏈接中指定的玩笑模擬
Create a setupJest file to setup the mock or add this to an existing setupFile. :
To setup for all tests
require('jest-fetch-mock').enableMocks()
Add the setupFile to your jest config in package.json:
"jest": {
"automock": false,
"setupFiles": [
"./setupJest.js"
]
}
因為這似乎是唯一的情況,其中 fetch 將嘗試對 API 進行實際調用,而不是給出模擬響應,從而導致失敗。
您甚至可以為特定的測試文件啟用模擬
import fetchMock from "jest-fetch-mock";
require('jest-fetch-mock').enableMocks();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.