-
-
Save dbani-dev/2cd546a239f8cfd3aa588ac63bf709f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PollingBase { | |
poll = async ({ fn, validate, interval, maxAttempts = 10 }) => { | |
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) | |
for (let attempts = 0; attempts < maxAttempts; attempts++) { | |
try { | |
const result = await fn() | |
if (validate(result)) { | |
return result | |
} | |
} catch (err) { | |
throw new Error(`Function error: ${err.message}`) | |
} | |
await sleep(interval) | |
} | |
throw new Error('Polling: exceeded max attempts') | |
} | |
} | |
// jest.setTimeout(10000) | |
describe('Polling Base', () => { | |
it('happy path', async () => { | |
const fn = jest.fn() | |
const validate = value => (value === 'success' ? true : false) | |
fn.mockResolvedValueOnce('requested') | |
.mockResolvedValueOnce('requested') | |
.mockResolvedValueOnce('requested') | |
.mockResolvedValueOnce('success') | |
const base = new PollingBase() | |
await base.poll({ | |
fn, | |
validate, | |
interval: 100, | |
maxAttempts: 4 | |
}) | |
expect(fn).toHaveBeenCalledTimes(4) | |
}) | |
it('fn throws', async () => { | |
const fn = jest.fn() | |
const validate = value => (value === 'success' ? true : false) | |
fn.mockResolvedValueOnce('requested').mockRejectedValue(new Error('Error!')) | |
const base = new PollingBase() | |
await expect( | |
base.poll({ | |
fn, | |
validate, | |
interval: 100, | |
maxAttempts: 4 | |
}) | |
).rejects.toThrowError('Function error: Error!') | |
expect(fn).toHaveBeenCalledTimes(2) | |
}) | |
it('fn returns invalid', async () => { | |
const fn = jest.fn() | |
const validate = value => (value === 'success' ? true : false) | |
fn.mockResolvedValue('invalid') | |
const base = new PollingBase() | |
await expect( | |
base.poll({ | |
fn, | |
validate, | |
interval: 100, | |
maxAttempts: 4 | |
}) | |
).rejects.toThrowError('Polling: exceeded max attempts') | |
expect(fn).toHaveBeenCalledTimes(4) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment