Skip to content

Instantly share code, notes, and snippets.

@alexlouden
Forked from dbani-dev/poll.js
Created April 6, 2022 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexlouden/e46884552798fde2330ecbbebe8953c2 to your computer and use it in GitHub Desktop.
Save alexlouden/e46884552798fde2330ecbbebe8953c2 to your computer and use it in GitHub Desktop.
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