Skip to content

Commit

Permalink
simplify wait implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
kentcdodds committed Mar 3, 2020
1 parent 4a9b025 commit d7789a4
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 19 deletions.
11 changes: 11 additions & 0 deletions src/__tests__/wait.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,14 @@ test('wait defaults to a noop callback', async () => {
await wait()
expect(handler).toHaveBeenCalledTimes(1)
})

test('can timeout after the given timeout time', async () => {
const error = new Error('throws every time')
const result = await wait(
() => {
throw error
},
{timeout: 8, interval: 5},
).catch(e => e)
expect(result).toBe(error)
})
3 changes: 3 additions & 0 deletions src/wait-for-element.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import {wait} from './wait'

// deprecated... TODO: remove this method. People should use a find* query or
// wait instead the reasoning is that this doesn't really do anything useful
// that you can't get from using find* or wait.
async function waitForElement(callback, options) {
if (!callback) {
throw new Error('waitForElement requires a callback as the first parameter')
Expand Down
23 changes: 4 additions & 19 deletions src/wait.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,20 @@ function wait(
} = {},
) {
if (interval < 1) interval = 1
const maxTries = Math.ceil(timeout / interval)
let tries = 0
return new Promise((resolve, reject) => {
let lastError, lastTimer
let lastError
const overallTimeoutTimer = setTimeout(onTimeout, timeout)
const intervalId = setInterval(checkCallback, interval)

const observer = newMutationObserver(checkCallback)
runWithRealTimers(() =>
observer.observe(container, mutationObserverOptions),
)
checkCallback()

function onDone(error, result) {
clearTimeout(overallTimeoutTimer)
clearTimeout(lastTimer)
clearInterval(intervalId)
setImmediate(() => observer.disconnect())
if (error) {
reject(error)
Expand All @@ -58,21 +58,6 @@ function wait(
function onTimeout() {
onDone(lastError || new Error('Timed out in wait.'), null)
}

function startTimer() {
lastTimer = setTimeout(() => {
tries++
checkCallback()
if (tries > maxTries) {
onTimeout()
return
}
startTimer()
}, interval)
}

checkCallback()
startTimer()
})
}

Expand Down

0 comments on commit d7789a4

Please sign in to comment.