Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!