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?