Skip to content

Instantly share code, notes, and snippets.

@AlicanC
Last active July 19, 2017 23:40
Show Gist options
  • Save AlicanC/03504ea4a39931c35acfdec0979a8c94 to your computer and use it in GitHub Desktop.
Save AlicanC/03504ea4a39931c35acfdec0979a8c94 to your computer and use it in GitHub Desktop.
doWithRetries
/* @flow */
export default async function doWithRetries<TFnResolveValue>(
retryCount: number,
fn: () => Promise<TFnResolveValue>,
): Promise<TFnResolveValue> {
let retriesLeft = retryCount;
let lastError;
do {
try {
// eslint-disable-next-line no-await-in-loop
return await fn();
} catch (error) {
lastError = error;
retriesLeft -= 1;
}
} while (retriesLeft >= 0);
throw lastError;
}
/* @flow */
import doWithRetries from './doWithRetries';
it.concurrent('calls fn at least once', async () => {
const mockFn = jest.fn();
await doWithRetries(-1, mockFn);
expect(mockFn).toHaveBeenCalledTimes(1);
});
it.concurrent('retries correct amount of times', async () => {
const mockFn = jest.fn(async () => { throw new Error('Error'); });
try {
await doWithRetries(4, mockFn);
} catch (error) {
// Ignore
}
expect(mockFn).toHaveBeenCalledTimes(5);
});
it.concurrent('rejects with correct error', async () => {
const mockError = new Error('Error');
const mockFn = jest.fn(async () => { throw mockError; });
try {
await doWithRetries(0, mockFn);
} catch (error) {
expect(error).toEqual(mockError);
}
});
it.concurrent('resolves with correct value', async () => {
const mockValue = Symbol('Value');
const mockFn = jest.fn(async () => mockValue);
expect(await doWithRetries(0, mockFn)).toEqual(mockValue);
});
it.concurrent('resolves with correct value after retries', async () => {
const mockValue = Symbol('Value');
const mockFn = jest.fn(async () => {
// Resolve on 4th retry (5 = 1st run + 4 retries)
if (mockFn.mock.calls.length === 5) {
return mockValue;
}
throw new Error('Error');
});
expect(await doWithRetries(4, mockFn)).toEqual(mockValue);
expect(mockFn).toHaveBeenCalledTimes(5);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment