【发布时间】:2022-01-20 22:02:59
【问题描述】:
这是我要测试的函数,它需要一个令牌和一个描述作为道具。通常在 React 代码中,我可以从 useContext 获取令牌。
export const updateUserProfileAbout = async (
token,
description
) => {
const dataUpdateTemplateDescriptionRes = await patchData(`me/`, token, {
about:description,
});
const dataUpdateTemplateDescriptionJson = await dataUpdateTemplateDescriptionRes.json();
return dataUpdateTemplateDescriptionJson;
};
这是我的自定义 patchData 函数:
const patchData = async (urn, token, data = "") => {
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${token.access}`,
};
const body = data ? JSON.stringify(data) : null;
let response;
if (body) {
response = await fetch(`${host}/api/${urn}`, {
method: "PATCH",
headers,
body,
});
} else {
response = await fetch(`${host}/api/${urn}`, {
method: "PATCH",
headers,
});
}
if (!response.ok) throw new Error(response.status);
return response;
};
【问题讨论】:
-
您听说过 Mock API(例如 Mock Axios)吗?
-
@TanNguyen 是的,我用 Axios 和 Fetch API 对 mock API 做了一些研究。但是,我不知道如何使用令牌模拟 API 或开玩笑地使用 React ContextAPI。
-
尝试使用关键字“ReactContext”、“Jest”进行谷歌搜索,找到了一些:stackoverflow.com/questions/54292298/jest-mock-react-context
标签: javascript reactjs unit-testing jestjs fetch-api