forked from cypress-io/cypress-example-recipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout.js
64 lines (51 loc) · 1.62 KB
/
timeout.js
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
/// <reference types="cypress" />
/* eslint-disable no-console */
/**
* Converts seconds to milliseconds
* @param {number} n Seconds to convert
*/
export const seconds = (n) => n * 1000
// keep an object with timers for tests where we set
// the timeout to avoid setting multiple timers
global.timers = new Map()
/**
* Stops the current Cypress test if it takes longer than the provided timeout
* @param {number} ms Test timeout in milliseconds
* @example
* // stop and fail the test if it runs for longer than 10 seconds
* testTimeout(10 * 1000)
*/
export function testTimeout (ms, test) {
// get the current test reference using
// the cy.state() magic method
const currentTest = cy.state('runnable') || test
if (!currentTest) {
throw new Error('Could not determine current test')
}
if (global.timers.has(currentTest)) {
console.log('removing existing timer for test', currentTest)
clearTimeout(global.timers.get(currentTest))
global.timers.delete(currentTest)
}
const startedAt = +new Date()
const timer = setTimeout(() => {
const testNow = cy.state('runnable')
console.log('test started', currentTest)
console.log('test now', testNow)
if (currentTest !== testNow) {
// different test already
return
}
console.log('test now state', testNow.state)
if (testNow.state) {
// test has finished
return
}
const timeNow = +new Date()
console.log('elapsed %d limit %d', timeNow - startedAt, ms)
if (timeNow - startedAt >= ms) {
throw new Error(`Test ran longer than ${ms}ms`)
}
}, ms)
global.timers.set(currentTest, timer)
}