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

172
Vistas
How to Test useEffect Fetch with Jest in React

How do I test my useEffect Fetch with Jest in React? I've tried looking for answers and found a code that I copied to try out but am still failing the test. I haven't used Jest before and am currently trying to implement it in a code I'm working on.

Here is my test inside my test.js file:

  it('Displays days from 1 to 31', async () => {
    expect(useEffectTest).toBe([{ day: 1 }]);
  });

And here is the useEffect in another component called calendar.jsx:

 const useEffectTest = () => {
  const [daysData, setDaysData] = useState([]);

  useEffect(() => {
    fetch('http://localhost:5001/chocolates')
      .then((resp) => resp.json())
      .then((data) => setDaysData(data));
  }, []);

  console.log(daysData);
};

I want to test if the fetched api is acquiring this data from an array of objects:

{ day: 1, status: 'empty' || 'open' }

Thanks for any help in advance.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Firstly, you need to update your unit test to call your function, like this:

it('Displays days from 1 to 31', async () => {
    expect(useEffectTest()).toBe([{ day: 1 }]);
});

That's because expect needs to have the data returned from your useEffectTest function passed in to it.

However, this will still fail because your function isn't returning anything. So we need to update useEffectTest to return daysData, like this:

 const useEffectTest = () => {
  const [daysData, setDaysData] = useState([]);

  useEffect(() => {
    fetch('http://localhost:5001/chocolates')
      .then((resp) => resp.json())
      .then((data) => setDaysData(data));
  }, []);

  return daysData;
};

Next up, we usually don't want to make network requests from unit tests. That's because network requests can make unit tests slow, and brittle. For example, if your API server goes down, we would still want the unit tests to pass. To get around these problems we need to mock the fetch request. A popular way to mock fetch requests is with the jest-fetch-mock library.

about 4 years ago · Santiago Trujillo 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