【发布时间】:2021-08-31 17:45:58
【问题描述】:
我在 React/TS 中有一个通用的 FetchService,如下所示:
/* Generic Fetch Service */
const FetchService = {
call: async (url:string) => {
try {
return await fetch(url)
.then((res) => res.json())
.then((data) => { data.response});
} catch (e) {
throw Error(e);
}
}
}
export default FetchService
还有一个这样写的测试:
import FetchService from "../../services/Fetch.service";
it("should call Fetch Service", async () => {
const val = { json: async () => [{ data: { response: "aaa" } }] };
window.fetch = jest.fn().mockImplementationOnce((url) => {
if (url === "localhost") {
return Promise.resolve(val);
}
});
const data = await FetchService.call("localhost");
expect(data).toBe(undefined);
});
它确实成功覆盖了 success ,但它返回“未定义”,而不是我在测试响应时模拟的数据。如果我将 console.log 放入我的服务中,在 data.response 中,它将记录来自测试的“aaa”。
我做错了什么?
我已经在 StackOverflow 中尝试了所有答案,以及一些教程,但没有任何效果。
使用 Jest Docs 也没有多大帮助。
谁能帮帮我?
谢谢。
编辑:
感谢这里的两个答案解决了
/* Generic Fetch Service */
const FetchService = {
call: async (url: string) => {
try {
const response = await fetch(url);
const data = await response.json();
console.log(data.response, "data111");
return data.response;
} catch (err) {
throw err;
}
},
};
export default FetchService;
在测试中:
const val = {
json: async () => {
return { response: "aaa" };
},
};
it("should call Fetch Service", async () => {
window.fetch = jest.fn().mockImplementationOnce((url) => {
if (url === "localhost") {
return val;
}
});
const data = await FetchService.call("localhost");
expect(data).toBe("aaa");
});
【问题讨论】:
-
它是否调用
return Promise.resolve(val)?例如,如果您在同一 if 语句中将console.log('resolving', val)放在其上方? -
@A_A 它记录:
resolving { json: [AsyncFunction: json] }
标签: reactjs typescript unit-testing jestjs