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

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