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

166
Visualizações
Issues with async tests using fetch and spyOn in jest

I am having an issue where the final case of the test.each block below seems to run with the real implementation of fetch() rather than the spy version.

  describe('renders correct number of components', () => {
    afterEach(() => {
      jest.restoreAllMocks();
    });

    test.each([1,2,3,4])('renders %i components', async (componentCount) => {
      jest.spyOn(window, 'fetch').mockResolvedValueOnce({
        json: async () => ({ components: componentCount })
      } as Response);

      render(<ParentComponent />);
      
      expect(await screen.findAllByText(/my component/i)).toHaveLength(componentCount);
    });
  });

The real implementation is:

  const getSomeData = async (): Promise<ComponentData> => {
    const res = await fetch('http://localhost:8080', { method: "GET" });
    return res.json();
  }

When I run the tests the first 3 pass fine, however the 4th throws a Error: connect ECONNREFUSED 127.0.0.1:8080. If I remove the 4th test the same happens with the 3rd.

If I change http://localhost:8080 to something like https://google.com I get a warning about a 'worker process failing to exit gracefully' but the tests all pass and there are no errors.

It seems to me that somehow the restored fetch() is making it through to the final test without being remocked by spyOn() but I can't for the life of me see how.

about 4 years ago · Juan Pablo Isaza
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