【问题标题】:How can I write unit test for api call with token using React, Jest and React-testing-library?如何使用 React、Jest 和 React-testing-library 为带有令牌的 api 调用编写单元测试?
【发布时间】: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


【解决方案1】:

经过一天的研究,虽然我可能错了,但我认为在前端单元测试时我不必关心令牌或授权。我只需要 jest.fn() 来模拟函数和 jest.spyOn(global, "fetch") 来跟踪 fetch API。

有关更多信息,以下是我阅读的一些参考资料:

https://codewithhugo.com/jest-fn-spyon-stub-mock/

https://dev.to/qmenoret/mocks-and-spies-with-jest-32gf

https://www.pluralsight.com/guides/how-does-jest.fn()-work

https://www.loupetestware.com/post/mocking-api-calls-with-jest

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 您好,能否请您发布更新后的代码?
猜你喜欢
  • 2021-07-02
  • 2021-02-11
  • 2021-02-28
  • 2020-03-22
  • 2022-06-22
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多