aboutsummaryrefslogtreecommitdiffstats
path: root/test/lib/util.js
blob: 858565bb95d386e55139978fce145fa78a0797e3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
module.exports = {
  timeout,
  queryAsync,
  findAsync,
  pollUntilTruthy,
}

function timeout (time) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, time || 1500)
  })
}

async function findAsync (container, selector, opts) {
  try {
    return await pollUntilTruthy(() => {
      const result = container.find(selector)
      if (result.length > 0) return result
    }, opts)
  } catch (err) {
    throw new Error(`Failed to find element within interval: "${selector}"`)
  }
}

async function queryAsync (jQuery, selector, opts) {
  try {
    return await pollUntilTruthy(() => {
      const result = jQuery(selector)
      if (result.length > 0) return result
    }, opts)
  } catch (err) {
    throw new Error(`Failed to find element within interval: "${selector}"`)
  }
}

async function pollUntilTruthy (fn, opts = {}) {
  const pollingInterval = opts.pollingInterval || 100
  const timeoutInterval = opts.timeoutInterval || 5000
  const start = Date.now()
  let result
  while (!result) {
    // check if timedout
    const now = Date.now()
    if ((now - start) > timeoutInterval) {
      throw new Error(`pollUntilTruthy - failed to return truthy within interval`)
    }
    // check for result
    result = fn()
    // run again after timeout
    await timeout(pollingInterval, timeoutInterval)
  }
  return result
}