All files / webdriverio/src/utils Timer.js

94.44% Statements 51/54
86.36% Branches 19/22
92.31% Functions 12/13
96.23% Lines 51/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131    70x                         23x 23x 23x 23x 23x             23x       23x 23x 23x     23x   23x       23x 23x 23x 16x   7x     23x       5x       5x 5x 5x         47x 27x   47x       21x       42x   42x 3x 2x     1x     39x 33x 6x         42x 42x     42x 8x 8x 8x 8x       34x 34x     34x     34x 21x   13x 13x 13x         34x       5x          
import { hasWdioSyncSupport, runFnInFiberContext } from '@wdio/config'
 
const TIMEOUT_ERROR = 'timeout'
 
/**
 * Promise-based Timer. Execute fn every tick.
 * When fn is resolved — timer will stop
 * @param {Number} delay - delay between ticks
 * @param {Number} timeout - after that time timer will stop
 * @param {Function} fn - function that returns promise. will execute every tick
 * @param {Boolean} leading - should be function invoked on start
 * @return {promise} Promise-based Timer.
 */
class Timer {
    constructor (delay, timeout, fn, leading) {
        this._delay = delay
        this._timeout = timeout
        this._fn = fn
        this._leading = leading
        this._conditionExecutedCnt = 0
 
        /**
         * only wrap waitUntil condition if:
         *  - wdio-sync is installed
         *  - function name is not async
         */
        Iif (hasWdioSyncSupport && !fn.name.includes('async')) {
            this._fn = () => runFnInFiberContext(fn)()
        }
 
        const retPromise = new Promise((resolve, reject) => {
            this._resolve = resolve
            this._reject = reject
        })
 
        this.start()
 
        return retPromise
    }
 
    start () {
        this._start = Date.now()
        this._ticks = 0
        if (this._leading) {
            this.tick()
        } else {
            this._timeoutId = setTimeout(this.tick.bind(this), this._delay)
        }
 
        this._mainTimeoutId = setTimeout(() => {
            /**
             * make sure that condition was executed at least once
             */
            Iif (!this.wasConditionExecuted()) {
                return
            }
 
            const reason = this.lastError || new Error(TIMEOUT_ERROR)
            this._reject(reason)
            this.stop()
        }, this._timeout)
    }
 
    stop () {
        if (this._timeoutId) {
            clearTimeout(this._timeoutId)
        }
        this._timeoutId = null
    }
 
    stopMain () {
        clearTimeout(this._mainTimeoutId)
    }
 
    tick () {
        const result = this._fn()
 
        if (typeof result.then !== 'function') {
            if (!result) {
                return this.checkCondition(new Error('return value was never truthy'))
            }
 
            return this.checkCondition(null, result)
        }
 
        result.then(
            (res) => this.checkCondition(null, res),
            (err) => this.checkCondition(err)
        )
    }
 
    checkCondition (err, res) {
        ++this._conditionExecutedCnt
        this.lastError = err
 
        // resolve timer only on truthy values
        if (res) {
            this._resolve(res)
            this.stop()
            this.stopMain()
            return
        }
 
        // autocorrect timer
        let diff = (Date.now() - this._start) - (this._ticks++ * this._delay)
        let delay = Math.max(0, this._delay - diff)
 
        // clear old timeoutID
        this.stop()
 
        // check if we have time to one more tick
        if (this.hasTime(delay)) {
            this._timeoutId = setTimeout(this.tick.bind(this), delay)
        } else {
            this.stopMain()
            const reason = this.lastError || new Error(TIMEOUT_ERROR)
            this._reject(reason)
        }
    }
 
    hasTime (delay) {
        return (Date.now() - this._start + delay) <= this._timeout
    }
 
    wasConditionExecuted () {
        return this._conditionExecutedCnt > 0
    }
}
 
export default Timer