jestjs - 如何模拟调用 fetch() 并返回响应 obj 的函数?
问题描述
export const fetchSomeData = async (): Promise<DataInterface> => {
try {
const url = `/api/someRoute`;
const res = await fnThatCallsFetch({
url,
method: 'GET'
});
const resData = await res.json();
const someData= resData.data;
if (res.status === 200 && someData) {
return someData;
} else {
throw new Error('Could not fetch info');
}
} catch (e) {
throw e;
}
};
fnThatCallsFetch 是一个调用 fetch() 的函数。如何模拟 fnThatCallsFetch 使其返回一些模拟数据?
目前我正在寻找间谍,但我不知道如何模拟响应对象,因为打字稿不会让我只模拟 json()。
const spyOn = jest.spyOn(fetchFn, 'fnThatCallsFetch').mockResolvedValue({
json: jest.fn().mockResolvedValue({
data: { name: '006-100' }
})
})
const data = await fetchSomeData ();
expect(data).toEqual({ name: '006-100' });
解决方案
推荐阅读
- c# - 为什么不编译?无法从“X”转换?到“X”
- c# - 在 C# 中是否可以通过属性存在进行模式匹配?
- python - 当我们在 Python 中不提及类时
- istio - ISTIO External Auth : '503 上游连接错误或在标头之前断开/重置。重置原因:通过 HTTPS 访问时连接终止根'
- android-studio - 我如何在 android studio 的 kotlin aproject 中使用 java jep perser?
- javascript - 如何在箱线图高图中将函数设置为最大值
- checkbox - 在反应中打开和关闭模式后如何保存复选框的标记?
- apache-nifi - 使用 NiFi 处理器计算文件中的文件数和行数
- linux - 删除固定宽度文件中的重复项,该文件除最后一次出现外具有多个键列
- java - Liferay 7.3 - org.hibernate.MappingException:找不到实体类