Skip to content

Commit 2a4b073

Browse files
authored
feat: check for common errors when using the wrong test environment (#8245)
1 parent b7cd432 commit 2a4b073

8 files changed

Lines changed: 262 additions & 6 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
### Features
44

5+
- `[jest-message-util]` Check for common errors when using the wrong test environment ([#8245](https://github.com/facebook/jest/pull/8245))
6+
57
### Fixes
68

79
- `[jest-circus]` Fix type ellision of jest-runtime imports ([#9717](https://github.com/facebook/jest/pull/9717))
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
// Jest Snapshot v1, https://goo.gl/fbAQLP
2+
3+
exports[`Wrong globals for environment print useful error for document 1`] = `
4+
FAIL __tests__/node.js
5+
✕ use document
6+
○ skipped use window
7+
○ skipped use navigator
8+
9+
● use document
10+
11+
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/en/configuration#testenvironment-string.
12+
Consider using the "jsdom" test environment.
13+
14+
ReferenceError: document is not defined
15+
16+
14 |
17+
15 | test('use document', () => {
18+
> 16 | const div = document.createElement('div');
19+
| ^
20+
17 |
21+
18 | console.log(div);
22+
19 |
23+
24+
at Object.document (__tests__/node.js:16:15)
25+
`;
26+
27+
exports[`Wrong globals for environment print useful error for navigator 1`] = `
28+
FAIL __tests__/node.js
29+
use navigator
30+
skipped use document
31+
skipped use window
32+
33+
use navigator
34+
35+
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/en/configuration#testenvironment-string.
36+
Consider using the "jsdom" test environment.
37+
38+
ReferenceError: navigator is not defined
39+
40+
30 |
41+
31 | test('use navigator', () => {
42+
> 32 | const userAgent = navigator.userAgent;
43+
| ^
44+
33 |
45+
34 | console.log(userAgent);
46+
35 |
47+
48+
at Object.navigator (__tests__/node.js:32:21)
49+
`;
50+
51+
exports[`Wrong globals for environment print useful error for unref 1`] = `
52+
FAIL __tests__/jsdom.js
53+
use unref
54+
55+
use unref
56+
57+
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/en/configuration#testenvironment-string.
58+
Consider using the "node" test environment.
59+
60+
TypeError: setTimeout(...).unref is not a function
61+
62+
11 |
63+
12 | test('use unref', () => {
64+
> 13 | setTimeout(() => {}, 0).unref();
65+
| ^
66+
14 |
67+
15 | expect(1).toBe(1);
68+
16 | });
69+
70+
at Object.unref (__tests__/jsdom.js:13:27)
71+
`;
72+
73+
exports[`Wrong globals for environment print useful error for window 1`] = `
74+
FAIL __tests__/node.js
75+
use window
76+
skipped use document
77+
skipped use navigator
78+
79+
use window
80+
81+
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/en/configuration#testenvironment-string.
82+
Consider using the "jsdom" test environment.
83+
84+
ReferenceError: window is not defined
85+
86+
22 |
87+
23 | test('use window', () => {
88+
> 24 | const location = window.location;
89+
| ^
90+
25 |
91+
26 | console.log(location);
92+
27 |
93+
94+
at Object.window (__tests__/node.js:24:20)
95+
`;
96+
97+
exports[`Wrong globals for environment print useful error when it explodes during evaluation 1`] = `
98+
FAIL __tests__/beforeTest.js
99+
Test suite failed to run
100+
101+
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/en/configuration#testenvironment-string.
102+
Consider using the "jsdom" test environment.
103+
104+
ReferenceError: document is not defined
105+
106+
11 | /* eslint-env browser */
107+
12 |
108+
> 13 | const div = document.createElement('div');
109+
| ^
110+
14 |
111+
15 | console.log(div);
112+
16 |
113+
114+
at Object.document (__tests__/beforeTest.js:13:13)
115+
`;

e2e/__tests__/wrongEnv.test.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
import wrap from 'jest-snapshot-serializer-raw';
9+
import runJest from '../runJest';
10+
import {extractSummary} from '../Utils';
11+
12+
function assertFailuresAndSnapshot(args: Array<string>) {
13+
const result = runJest('wrong-env', args);
14+
expect(result.exitCode).toBe(1);
15+
expect(wrap(extractSummary(result.stderr).rest)).toMatchSnapshot();
16+
}
17+
18+
describe('Wrong globals for environment', () => {
19+
it('print useful error for window', () => {
20+
assertFailuresAndSnapshot(['node', '-t=window']);
21+
});
22+
23+
it('print useful error for document', () => {
24+
assertFailuresAndSnapshot(['node', '-t=document']);
25+
});
26+
27+
it('print useful error for navigator', () => {
28+
assertFailuresAndSnapshot(['node', '-t=navigator']);
29+
});
30+
31+
it('print useful error for unref', () => {
32+
assertFailuresAndSnapshot(['jsdom', '-t=unref']);
33+
});
34+
35+
it('print useful error when it explodes during evaluation', () => {
36+
assertFailuresAndSnapshot(['beforeTest']);
37+
});
38+
});
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @jest-environment node
8+
*
9+
*/
10+
11+
/* eslint-env browser */
12+
13+
const div = document.createElement('div');
14+
15+
console.log(div);
16+
17+
test('stub', () => expect(1).toBe(1));

e2e/wrong-env/__tests__/jsdom.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @jest-environment jsdom
8+
*/
9+
10+
'use strict';
11+
12+
test('use unref', () => {
13+
setTimeout(() => {}, 0).unref();
14+
15+
expect(1).toBe(1);
16+
});

e2e/wrong-env/__tests__/node.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @jest-environment node
8+
*
9+
*/
10+
11+
/* eslint-env browser */
12+
13+
'use strict';
14+
15+
test('use document', () => {
16+
const div = document.createElement('div');
17+
18+
console.log(div);
19+
20+
expect(1).toBe(1);
21+
});
22+
23+
test('use window', () => {
24+
const location = window.location;
25+
26+
console.log(location);
27+
28+
expect(1).toBe(1);
29+
});
30+
31+
test('use navigator', () => {
32+
const userAgent = navigator.userAgent;
33+
34+
console.log(userAgent);
35+
36+
expect(1).toBe(1);
37+
});

e2e/wrong-env/package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"jest": {}
3+
}

packages/jest-message-util/src/index.ts

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,30 @@ const getRenderedCallsite = (
9292

9393
const blankStringRegexp = /^\s*$/;
9494

95+
function checkForCommonEnvironmentErrors(error: string) {
96+
if (
97+
error.includes('ReferenceError: document is not defined') ||
98+
error.includes('ReferenceError: window is not defined') ||
99+
error.includes('ReferenceError: navigator is not defined')
100+
) {
101+
return warnAboutWrongTestEnvironment(error, 'jsdom');
102+
} else if (error.includes('.unref is not a function')) {
103+
return warnAboutWrongTestEnvironment(error, 'node');
104+
}
105+
106+
return error;
107+
}
108+
109+
function warnAboutWrongTestEnvironment(error: string, env: 'jsdom' | 'node') {
110+
return (
111+
chalk.bold.red(
112+
`The error below may be caused by using the wrong test environment, see ${chalk.dim.underline(
113+
'https://jestjs.io/docs/en/configuration#testenvironment-string',
114+
)}.\nConsider using the "${env}" test environment.\n\n`,
115+
) + error
116+
);
117+
}
118+
95119
// ExecError is an error thrown outside of the test suite (not inside an `it` or
96120
// `before/after each` hooks). If it's thrown, none of the tests in the file
97121
// are executed.
@@ -126,6 +150,8 @@ export const formatExecError = (
126150
message = separated.message;
127151
}
128152

153+
message = checkForCommonEnvironmentErrors(message);
154+
129155
message = indentAllLines(message, MESSAGE_INDENT);
130156

131157
stack =
@@ -285,19 +311,21 @@ export const formatStackTrace = (
285311
return `${renderedCallsite}\n${stacktrace}`;
286312
};
287313

314+
type FailedResults = Array<{
315+
content: string;
316+
result: AssertionResult;
317+
}>;
318+
288319
export const formatResultsErrors = (
289320
testResults: Array<AssertionResult>,
290321
config: StackTraceConfig,
291322
options: StackTraceOptions,
292323
testPath?: Path,
293324
): string | null => {
294-
type FailedResults = Array<{
295-
content: string;
296-
result: AssertionResult;
297-
}>;
298-
299325
const failedResults: FailedResults = testResults.reduce((errors, result) => {
300-
result.failureMessages.forEach(content => errors.push({content, result}));
326+
result.failureMessages
327+
.map(checkForCommonEnvironmentErrors)
328+
.forEach(content => errors.push({content, result}));
301329
return errors;
302330
}, [] as FailedResults);
303331

0 commit comments

Comments
 (0)