【发布时间】:2021-09-24 00:58:40
【问题描述】:
我正在使用 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
})
})
【问题讨论】:
-
你为什么要创建模拟来作为
.then/.catch回调传递?使用jestjs.io/docs/asynchronous#resolves--rejects。另请注意mockResponseONce看起来像是一个错字 - 你能给出实际设置的minimal reproducible example 吗?
标签: reactjs unit-testing jestjs jest-fetch-mock