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

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

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 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