Skip to content

Commit

Permalink
test(assertWithTimeout): add async assertion util
Browse files Browse the repository at this point in the history
  • Loading branch information
levithomason committed Feb 19, 2018
1 parent d9b92da commit 3d8c9b8
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react'

import TransitionablePortal from 'src/addons/TransitionablePortal/TransitionablePortal'
import * as common from 'test/specs/commonTests'
import { domEvent, sandbox } from 'test/utils'
import { domEvent, sandbox, assertWithTimeout } from 'test/utils'

// ----------------------------------------
// Wrapper
Expand Down Expand Up @@ -77,12 +77,10 @@ describe('TransitionablePortal', () => {
wrapper.find('button').simulate('click')
domEvent.click(document.body)

setTimeout(() => {
assertWithTimeout(() => {
onClose.should.have.been.calledOnce()
onClose.should.have.been.calledWithMatch(null, { portalOpen: false })

done()
}, 10)
}, done)
})

it('changes `portalOpen` to false', () => {
Expand Down Expand Up @@ -111,16 +109,14 @@ describe('TransitionablePortal', () => {
)

wrapper.setProps({ open: false })
setTimeout(() => {
assertWithTimeout(() => {
onHide.should.have.been.calledOnce()
onHide.should.have.been.calledWithMatch(null, {
...quickTransition,
portalOpen: false,
transitionVisible: false,
})

done()
}, 10)
}, done)
})
})

Expand Down
28 changes: 28 additions & 0 deletions test/utils/assertWithTimeout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Repeatedly attempt to make an assertion over a period of time.
* If the assertion never passes, it will eventually throw.
* Good for tests with unknown or unreliable execution times.
*
* @param {function} assertion - A callback that makes test assertions.
* @param {function} done - The done callback.
*/
const assertWithTimeout = (assertion, done) => {
const timeout = 1000 * 2
const start = Date.now()

const assert = () => {
try {
assertion()
done()
} catch (err) {
if (Date.now() - start >= timeout) throw err

setTimeout(assert, 10)
}
}

assert()
}


export default assertWithTimeout
1 change: 1 addition & 0 deletions test/utils/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { default as assertBodyClasses } from './assertBodyClasses'
export { default as assertWithTimeout } from './assertWithTimeout'
export * from './assertNodeContains'
export { default as consoleUtil } from './consoleUtil'
export { default as domEvent } from './domEvent'
Expand Down

0 comments on commit 3d8c9b8

Please sign in to comment.