Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

297
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda