Use process timer for jest timeout testing

This commit is contained in:
Paul Slaughter 2019-05-08 09:36:38 -05:00
parent 603412af27
commit ad7d62e1ac
No known key found for this signature in database
GPG Key ID: DF5690803C68282A
1 changed files with 17 additions and 10 deletions

View File

@ -1,24 +1,31 @@
let testTimeoutInMs;
const NS_PER_SEC = 1e9;
const NS_PER_MS = 1e6;
export const setTestTimeout = newTimeoutInMs => {
testTimeoutInMs = newTimeoutInMs;
jest.setTimeout(newTimeoutInMs);
let testTimeoutNS;
export const setTestTimeout = newTimeoutMS => {
testTimeoutNS = newTimeoutMS * NS_PER_MS;
jest.setTimeout(newTimeoutMS);
};
export const initializeTestTimeout = defaultTimeoutInMs => {
setTestTimeout(defaultTimeoutInMs);
export const initializeTestTimeout = defaultTimeoutMS => {
setTestTimeout(defaultTimeoutMS);
let testStartTime;
// https://github.com/facebook/jest/issues/6947
beforeEach(() => {
testStartTime = Date.now();
testStartTime = process.hrtime();
});
afterEach(() => {
const elapsedTimeInMs = Date.now() - testStartTime;
if (elapsedTimeInMs > testTimeoutInMs) {
throw new Error(`Test took too long (${elapsedTimeInMs}ms > ${testTimeoutInMs}ms)!`);
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)!`,
);
}
});
};