Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix bug when setTimeout is mocked #3769

Merged
merged 1 commit into from
Jun 9, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions packages/jest-circus/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ const _makeTimeoutMessage = (timeout, isHook) =>
`Exceeded timeout of ${timeout}ms for a ${isHook ? 'hook' : 'test'}.\nUse jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.`,
);

// Global values can be overwritten by mocks or tests. We'll capture
// the original values in the variables before we require any files.
const {setTimeout, clearTimeout} = global;

const callAsyncFn = (
fn: AsyncFn,
testContext: ?TestContext,
Expand All @@ -124,8 +128,13 @@ const callAsyncFn = (
timeout,
}: {isHook?: ?boolean, test?: TestEntry, timeout: number},
): Promise<any> => {
let timeoutID;

return new Promise((resolve, reject) => {
setTimeout(() => reject(_makeTimeoutMessage(timeout, isHook)), timeout);
timeoutID = setTimeout(
() => reject(_makeTimeoutMessage(timeout, isHook)),
timeout,
);

// If this fn accepts `done` callback we return a promise that fullfills as
// soon as `done` called.
Expand Down Expand Up @@ -162,7 +171,18 @@ const callAsyncFn = (
// Otherwise this test is synchronous, and if it didn't throw it means
// it passed.
return resolve();
});
})
.then(() => {
// If timeout is not cleared/unrefed the node process won't exit until
// it's resolved.
timeoutID.unref && timeoutID.unref();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't know that was a thing.

clearTimeout(timeoutID);
})
.catch(error => {
timeoutID.unref && timeoutID.unref();
clearTimeout(timeoutID);
throw error;
});
};

const getTestDuration = (test: TestEntry): ?number => {
Expand Down