2022-08-10 16:06:30 +00:00
|
|
|
/// <reference types="cypress" />
|
|
|
|
|
/* eslint-disable no-console */
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Converts seconds to milliseconds
|
|
|
|
|
* @param {number} n Seconds to convert
|
|
|
|
|
*/
|
2022-08-16 05:42:31 +00:00
|
|
|
export const seconds = (n) => n * 1000;
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
// keep an object with timers for tests where we set
|
|
|
|
|
// the timeout to avoid setting multiple timers
|
|
|
|
|
global.timers = new Map();
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
/**
|
|
|
|
|
* 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) {
|
|
|
|
|
// get the current test reference using
|
|
|
|
|
// the cy.state() magic method
|
|
|
|
|
const currentTest = cy.state("runnable"); // || test
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
if (!currentTest) {
|
|
|
|
|
throw new Error("Could not determine current test");
|
|
|
|
|
}
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
if (global.timers.has(currentTest)) {
|
|
|
|
|
console.log("removing existing timer for test", currentTest);
|
|
|
|
|
clearTimeout(global.timers.get(currentTest));
|
|
|
|
|
global.timers.delete(currentTest);
|
|
|
|
|
}
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
const startedAt = +new Date();
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
const timer = setTimeout(() => {
|
|
|
|
|
const testNow = cy.state("runnable");
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
console.log("test started", currentTest);
|
|
|
|
|
console.log("test now", testNow);
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
if (currentTest !== testNow) {
|
|
|
|
|
// different test already
|
|
|
|
|
return;
|
|
|
|
|
}
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
console.log("test now state", testNow.state);
|
|
|
|
|
if (testNow.state) {
|
|
|
|
|
// test has finished
|
|
|
|
|
return;
|
|
|
|
|
}
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
const timeNow = +new Date();
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
console.log("elapsed %d limit %d", timeNow - startedAt, ms);
|
|
|
|
|
if (timeNow - startedAt >= ms) {
|
|
|
|
|
throw new Error(`Test ran longer than ${ms}ms`);
|
|
|
|
|
}
|
|
|
|
|
}, ms);
|
2022-08-10 16:06:30 +00:00
|
|
|
|
2022-08-16 05:42:31 +00:00
|
|
|
global.timers.set(currentTest, timer);
|
|
|
|
|
}
|
2022-08-10 16:06:30 +00:00
|
|
|
|
|
|
|
|
//export default {testTimeout};
|