Skip to content

Commit

Permalink
Better error messages when the jest environment is used after teardow…
Browse files Browse the repository at this point in the history
…n by async code (jestjs#7756)
  • Loading branch information
olivierbeaulieu authored and captain-yossarian committed Jul 18, 2019
1 parent bfaa70b commit 48e37b9
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 21 deletions.
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

0 comments on commit 48e37b9

Please sign in to comment.