Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

296
Views
How can I write unit test for api call with token using React, Jest and React-testing-library?

Here is the function that I wanna test, it takes a token and a description as props. Normally in React code, I can get token from useContext.

export const updateUserProfileAbout = async (
  token,
  description
) => {
  const dataUpdateTemplateDescriptionRes = await patchData(`me/`, token, {
    about:description,
  });
  const dataUpdateTemplateDescriptionJson  = await dataUpdateTemplateDescriptionRes.json();
  return dataUpdateTemplateDescriptionJson;
};

And here is my custom patchData function:

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;
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

After one more day of researching, I might be wrong though but I don't think I have to care about token or authorization when unit testing for front-end. All I need is jest.fn() to mock function and jest.spyOn(global, "fetch") to track fetch API.

For more information, here are some references that I read:

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!