summaryrefslogtreecommitdiff
path: root/spec/frontend/helpers/timeout.js
blob: e74598ae20ac49edbb376437f79696bed442e6a3 (plain)
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
const NS_PER_SEC = 1e9;
const NS_PER_MS = 1e6;
const IS_DEBUGGING = process.execArgv.join(' ').includes('--inspect-brk');

let testTimeoutNS;

export const setTestTimeout = newTimeoutMS => {
  testTimeoutNS = newTimeoutMS * NS_PER_MS;
  jest.setTimeout(newTimeoutMS);
};

// Allows slow tests to set their own timeout.
// Useful for tests with jQuery, which is very slow in big DOMs.
let temporaryTimeoutNS = null;
export const setTestTimeoutOnce = newTimeoutMS => {
  temporaryTimeoutNS = newTimeoutMS * NS_PER_MS;
};

export const initializeTestTimeout = defaultTimeoutMS => {
  setTestTimeout(defaultTimeoutMS);

  let testStartTime;

  // https://github.com/facebook/jest/issues/6947
  beforeEach(() => {
    testStartTime = process.hrtime();
  });

  afterEach(() => {
    let timeoutNS = testTimeoutNS;
    if (Number.isFinite(temporaryTimeoutNS)) {
      timeoutNS = temporaryTimeoutNS;
      temporaryTimeoutNS = null;
    }

    const [seconds, remainingNs] = process.hrtime(testStartTime);
    const elapsedNS = seconds * NS_PER_SEC + remainingNs;

    // Disable the timeout error when debugging. It is meaningless because
    // debugging always takes longer than the test timeout.
    if (elapsedNS > timeoutNS && !IS_DEBUGGING) {
      throw new Error(
        `Test took too long (${elapsedNS / NS_PER_MS}ms > ${timeoutNS / NS_PER_MS}ms)!`,
      );
    }
  });
};