Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

295
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda