summaryrefslogtreecommitdiff
path: root/spec/frontend/helpers/timeout.js
blob: b30b7f1ce1e2c47ae318c7378eea135dbe1f0774 (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
const NS_PER_SEC = 1e9;
const NS_PER_MS = 1e6;

let testTimeoutNS;

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

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

  let testStartTime;

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

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

    if (elapsedNS > testTimeoutNS) {
      throw new Error(
        `Test took too long (${elapsedNS / NS_PER_MS}ms > ${testTimeoutNS / NS_PER_MS}ms)!`,
      );
    }
  });
};