Skip to content

Commit

Permalink
[CityOfZion#1318] PrepWork 1/2: Added util/poll.js unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ranbena committed Nov 28, 2018
1 parent c92b866 commit 0ffde19
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
33 changes: 33 additions & 0 deletions __tests__/util/poll.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import poll, { TimeoutError } from '../../app/util/poll'

describe('poll functionality', () => {
test('should stop when condition fulflled', async () => {
// 10 rounds of 10ms
const pollCfg = { attempts: 10, frequency: 10 }

// pulfill the poll condition after 5th attempt
let num = 5
const condition = jest.fn(() => {
return --num === 0 ? Promise.resolve(num) : Promise.reject()
})

// run poll, expect no exit by error
const result = await poll(condition, pollCfg)
// expect to have run 5/10 attempts
expect(condition).toHaveBeenCalledTimes(5)
})

test('should stop when max attempts reached', async () => {
// 10 rounds of 10ms
const pollCfg = { attempts: 10, frequency: 10 }
// always reject means poll is continuous
const condition = jest.fn(() => Promise.reject())

try {
await poll(condition, pollCfg) // run poll
} catch (e) {
expect(e.name).toBe(TimeoutError.name) // expect it to reach max attempts
expect(condition).toHaveBeenCalledTimes(11) // expect to have run 10 (+1) attempts
}
})
})
11 changes: 9 additions & 2 deletions app/util/poll.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,24 @@ import delay from './delay'
const DEFAULT_ATTEMPTS = Infinity
const DEFAULT_FREQUENCY = 1000

export class TimeoutError extends Error {
constructor() {
super('Poll reached maximum attempts')
this.name = 'TimeoutError'
}
}

export default function poll(
request,
{ attempts = DEFAULT_ATTEMPTS, frequency = DEFAULT_FREQUENCY } = {}
) {
return request().catch(function retry(err) {
return request().catch(function retry() {
// eslint-disable-next-line
if (attempts-- > 0) {
return delay(frequency)
.then(request)
.catch(retry)
}
throw err
throw new TimeoutError()
})
}

0 comments on commit 0ffde19

Please sign in to comment.