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

178
Views
Jest/fetch-mock ignoring setTimeout inside Promise

I built a function which will repeat a HTTP request 3 times every 1500ms if the the status is 5xx.

const fetchRetry = (url: string, options = {}, retries = 3, timeout = 1500) => {
  return new Promise((resolve) => {
    fetch(url, options).then((res) => {
      if (res.ok) return resolve(res);

      if (retries > 0 && res.status >= 500 && res.status < 600) {
        setTimeout(() => {
          resolve(fetchRetry(url, options, retries - 1, timeout));
        }, timeout);
      } else {
        return resolve(res);
      }
    });
  });
};

export default fetchRetry;

It works just fine on the browser, but is causing a lot of tests to fail.

This is an example of a test that I have:

fetchMock.postOnce("/my-api", {
  status: 503,
});

const expectedActions = [
  {
   itemRef: "sample",
  },
];

return store
  .dispatch(myAction.findRef(itemRef))
  .then(() => {
    expect(store.getActions()).toEqual(expectedActions);
  });

Basically I'm testing my code using jest and fetch-mock, as you can see, I'm mocking the api request and I'm waiting myAction.findRef(itemRef) (Promise) to be fulfilled.

I'm always receiving: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:.

If I remove setTimeout it will work. Which is bizarre.

I also tried to increment the jest.setTimeout.Timeout but with no luck.

Any ideas?

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!