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

Fixes 7099 - Better error messages when the jest environment is used after teardown by async code #7756

Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

- `[jest-resolve]`: Pass default resolver into custom resolvers ([#7714](https://github.com/facebook/jest/pull/7714))
- `[jest-cli]`: `global{Setup,Teardown}` use default export with es modules ([#7750](https://github.com/facebook/jest/pull/7750))
- `[jest-runtime]` Better error messages when the jest environment is used after teardown by async code ([#7756](https://github.com/facebook/jest/pull/7756))

### Fixes

Expand Down
13 changes: 13 additions & 0 deletions e2e/__tests__/__snapshots__/environmentAfterTeardown.test.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`prints useful error for environment methods after test is done 1`] = `
ReferenceError: You are trying to access a property or method of the Jest environment after it has been torn down.

9 | test('access environment methods after done', () => {
10 | setTimeout(() => {
> 11 | jest.clearAllTimers();
| ^
12 | }, 0);
13 | });
14 |
`;
24 changes: 24 additions & 0 deletions e2e/__tests__/environmentAfterTeardown.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import runJest from '../runJest';
import {wrap} from 'jest-snapshot-serializer-raw';

test('prints useful error for environment methods after test is done', () => {
const {stderr} = runJest('environment-after-teardown');
const interestingLines = stderr
.split('\n')
.slice(9, 18)
.join('\n');

expect(wrap(interestingLines)).toMatchSnapshot();
expect(stderr.split('\n')[9]).toBe(
'ReferenceError: You are trying to access a property or method of the Jest environment after it has been torn down.',
);
});
13 changes: 13 additions & 0 deletions e2e/environment-after-teardown/__tests__/afterTeardown.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';

test('access environment methods after done', () => {
setTimeout(() => {
jest.clearAllTimers();
}, 0);
});
5 changes: 5 additions & 0 deletions e2e/environment-after-teardown/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"jest": {
"testEnvironment": "node"
}
}
56 changes: 35 additions & 21 deletions packages/jest-runtime/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -684,19 +684,8 @@ class Runtime {
const runScript = this._environment.runScript(transformedFile.script);

if (runScript === null) {
const originalStack = new ReferenceError(
this._logFormattedReferenceError(
'You are trying to `import` a file after the Jest environment has been torn down.',
).stack
.split('\n')
// Remove this file from the stack (jest-message-utils will keep one line)
.filter(line => line.indexOf(__filename) === -1)
.join('\n');

const {message, stack} = separateMessageFromStack(originalStack);

console.error(
`\n${message}\n` +
formatStackTrace(stack, this._config, {noStackTrace: false}),
);
process.exitCode = 1;
return;
Expand Down Expand Up @@ -978,15 +967,26 @@ class Runtime {
return jestObject;
};

const _getFakeTimers = () => {
if (!this._environment.fakeTimers) {
this._logFormattedReferenceError(
'You are trying to access a property or method of the Jest environment after it has been torn down.',
);
process.exitCode = 1;
}

return this._environment.fakeTimers;
};

const jestObject = {
addMatchers: (matchers: Object) =>
this._environment.global.jasmine.addMatchers(matchers),
advanceTimersByTime: (msToRun: number) =>
this._environment.fakeTimers.advanceTimersByTime(msToRun),
_getFakeTimers().advanceTimersByTime(msToRun),
autoMockOff: disableAutomock,
autoMockOn: enableAutomock,
clearAllMocks,
clearAllTimers: () => this._environment.fakeTimers.clearAllTimers(),
clearAllTimers: () => _getFakeTimers().clearAllTimers(),
deepUnmock,
disableAutomock,
doMock: mock,
Expand All @@ -995,7 +995,7 @@ class Runtime {
fn,
genMockFromModule: (moduleName: string) =>
this._generateMock(from, moduleName),
getTimerCount: () => this._environment.fakeTimers.getTimerCount(),
getTimerCount: () => _getFakeTimers().getTimerCount(),
isMockFunction: this._moduleMocker.isMockFunction,
isolateModules,
mock,
Expand All @@ -1006,13 +1006,12 @@ class Runtime {
resetModules,
restoreAllMocks,
retryTimes,
runAllImmediates: () => this._environment.fakeTimers.runAllImmediates(),
runAllTicks: () => this._environment.fakeTimers.runAllTicks(),
runAllTimers: () => this._environment.fakeTimers.runAllTimers(),
runOnlyPendingTimers: () =>
this._environment.fakeTimers.runOnlyPendingTimers(),
runAllImmediates: () => _getFakeTimers().runAllImmediates(),
runAllTicks: () => _getFakeTimers().runAllTicks(),
runAllTimers: () => _getFakeTimers().runAllTimers(),
runOnlyPendingTimers: () => _getFakeTimers().runOnlyPendingTimers(),
runTimersToTime: (msToRun: number) =>
this._environment.fakeTimers.advanceTimersByTime(msToRun),
_getFakeTimers().advanceTimersByTime(msToRun),
setMock: (moduleName: string, mock: Object) =>
setMockFactory(moduleName, () => mock),
setTimeout,
Expand All @@ -1023,6 +1022,21 @@ class Runtime {
};
return jestObject;
}

_logFormattedReferenceError(errorMessage: string) {
const originalStack = new ReferenceError(errorMessage).stack
.split('\n')
// Remove this file from the stack (jest-message-utils will keep one line)
.filter(line => line.indexOf(__filename) === -1)
.join('\n');

const {message, stack} = separateMessageFromStack(originalStack);

console.error(
`\n${message}\n` +
formatStackTrace(stack, this._config, {noStackTrace: false}),
);
}
}

Runtime.ScriptTransformer = ScriptTransformer;
Expand Down