UNPKG

16.7 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', {
4 value: true
5});
6exports.separateMessageFromStack =
7 exports.indentAllLines =
8 exports.getTopFrame =
9 exports.getStackTraceLines =
10 exports.formatStackTrace =
11 exports.formatResultsErrors =
12 exports.formatPath =
13 exports.formatExecError =
14 void 0;
15var path = _interopRequireWildcard(require('path'));
16var _url = require('url');
17var _util = require('util');
18var _codeFrame = require('@babel/code-frame');
19var _chalk = _interopRequireDefault(require('chalk'));
20var fs = _interopRequireWildcard(require('graceful-fs'));
21var _micromatch = _interopRequireDefault(require('micromatch'));
22var _slash = _interopRequireDefault(require('slash'));
23var _stackUtils = _interopRequireDefault(require('stack-utils'));
24var _prettyFormat = require('pretty-format');
25function _interopRequireDefault(obj) {
26 return obj && obj.__esModule ? obj : {default: obj};
27}
28function _getRequireWildcardCache(nodeInterop) {
29 if (typeof WeakMap !== 'function') return null;
30 var cacheBabelInterop = new WeakMap();
31 var cacheNodeInterop = new WeakMap();
32 return (_getRequireWildcardCache = function (nodeInterop) {
33 return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
34 })(nodeInterop);
35}
36function _interopRequireWildcard(obj, nodeInterop) {
37 if (!nodeInterop && obj && obj.__esModule) {
38 return obj;
39 }
40 if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
41 return {default: obj};
42 }
43 var cache = _getRequireWildcardCache(nodeInterop);
44 if (cache && cache.has(obj)) {
45 return cache.get(obj);
46 }
47 var newObj = {};
48 var hasPropertyDescriptor =
49 Object.defineProperty && Object.getOwnPropertyDescriptor;
50 for (var key in obj) {
51 if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
52 var desc = hasPropertyDescriptor
53 ? Object.getOwnPropertyDescriptor(obj, key)
54 : null;
55 if (desc && (desc.get || desc.set)) {
56 Object.defineProperty(newObj, key, desc);
57 } else {
58 newObj[key] = obj[key];
59 }
60 }
61 }
62 newObj.default = obj;
63 if (cache) {
64 cache.set(obj, newObj);
65 }
66 return newObj;
67}
68var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
69var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
70var jestReadFile =
71 globalThis[Symbol.for('jest-native-read-file')] || fs.readFileSync;
72/**
73 * Copyright (c) Meta Platforms, Inc. and affiliates.
74 *
75 * This source code is licensed under the MIT license found in the
76 * LICENSE file in the root directory of this source tree.
77 */
78// stack utils tries to create pretty stack by making paths relative.
79const stackUtils = new _stackUtils.default({
80 cwd: 'something which does not exist'
81});
82let nodeInternals = [];
83try {
84 nodeInternals = _stackUtils.default.nodeInternals();
85} catch {
86 // `StackUtils.nodeInternals()` fails in browsers. We don't need to remove
87 // node internals in the browser though, so no issue.
88}
89const PATH_NODE_MODULES = `${path.sep}node_modules${path.sep}`;
90const PATH_JEST_PACKAGES = `${path.sep}jest${path.sep}packages${path.sep}`;
91
92// filter for noisy stack trace lines
93const JASMINE_IGNORE =
94 /^\s+at(?:(?:.jasmine-)|\s+jasmine\.buildExpectationResult)/;
95const JEST_INTERNALS_IGNORE =
96 /^\s+at.*?jest(-.*?)?(\/|\\)(build|node_modules|packages)(\/|\\)/;
97const ANONYMOUS_FN_IGNORE = /^\s+at <anonymous>.*$/;
98const ANONYMOUS_PROMISE_IGNORE = /^\s+at (new )?Promise \(<anonymous>\).*$/;
99const ANONYMOUS_GENERATOR_IGNORE = /^\s+at Generator.next \(<anonymous>\).*$/;
100const NATIVE_NEXT_IGNORE = /^\s+at next \(native\).*$/;
101const TITLE_INDENT = ' ';
102const MESSAGE_INDENT = ' ';
103const STACK_INDENT = ' ';
104const ANCESTRY_SEPARATOR = ' \u203A ';
105const TITLE_BULLET = _chalk.default.bold('\u25cf ');
106const STACK_TRACE_COLOR = _chalk.default.dim;
107const STACK_PATH_REGEXP = /\s*at.*\(?(:\d*:\d*|native)\)?/;
108const EXEC_ERROR_MESSAGE = 'Test suite failed to run';
109const NOT_EMPTY_LINE_REGEXP = /^(?!$)/gm;
110const indentAllLines = lines =>
111 lines.replace(NOT_EMPTY_LINE_REGEXP, MESSAGE_INDENT);
112exports.indentAllLines = indentAllLines;
113const trim = string => (string || '').trim();
114
115// Some errors contain not only line numbers in stack traces
116// e.g. SyntaxErrors can contain snippets of code, and we don't
117// want to trim those, because they may have pointers to the column/character
118// which will get misaligned.
119const trimPaths = string =>
120 string.match(STACK_PATH_REGEXP) ? trim(string) : string;
121const getRenderedCallsite = (fileContent, line, column) => {
122 let renderedCallsite = (0, _codeFrame.codeFrameColumns)(
123 fileContent,
124 {
125 start: {
126 column,
127 line
128 }
129 },
130 {
131 highlightCode: true
132 }
133 );
134 renderedCallsite = indentAllLines(renderedCallsite);
135 renderedCallsite = `\n${renderedCallsite}\n`;
136 return renderedCallsite;
137};
138const blankStringRegexp = /^\s*$/;
139function checkForCommonEnvironmentErrors(error) {
140 if (
141 error.includes('ReferenceError: document is not defined') ||
142 error.includes('ReferenceError: window is not defined') ||
143 error.includes('ReferenceError: navigator is not defined')
144 ) {
145 return warnAboutWrongTestEnvironment(error, 'jsdom');
146 } else if (error.includes('.unref is not a function')) {
147 return warnAboutWrongTestEnvironment(error, 'node');
148 }
149 return error;
150}
151function warnAboutWrongTestEnvironment(error, env) {
152 return (
153 _chalk.default.bold.red(
154 `The error below may be caused by using the wrong test environment, see ${_chalk.default.dim.underline(
155 'https://jestjs.io/docs/configuration#testenvironment-string'
156 )}.\nConsider using the "${env}" test environment.\n\n`
157 ) + error
158 );
159}
160
161// ExecError is an error thrown outside of the test suite (not inside an `it` or
162// `before/after each` hooks). If it's thrown, none of the tests in the file
163// are executed.
164const formatExecError = (
165 error,
166 config,
167 options,
168 testPath,
169 reuseMessage,
170 noTitle
171) => {
172 if (!error || typeof error === 'number') {
173 error = new Error(`Expected an Error, but "${String(error)}" was thrown`);
174 error.stack = '';
175 }
176 let message, stack;
177 let cause = '';
178 const subErrors = [];
179 if (typeof error === 'string' || !error) {
180 error || (error = 'EMPTY ERROR');
181 message = '';
182 stack = error;
183 } else {
184 message = error.message;
185 stack =
186 typeof error.stack === 'string'
187 ? error.stack
188 : `thrown: ${(0, _prettyFormat.format)(error, {
189 maxDepth: 3
190 })}`;
191 if ('cause' in error) {
192 const prefix = '\n\nCause:\n';
193 if (typeof error.cause === 'string' || typeof error.cause === 'number') {
194 cause += `${prefix}${error.cause}`;
195 } else if (
196 _util.types.isNativeError(error.cause) ||
197 error.cause instanceof Error
198 ) {
199 /* `isNativeError` is used, because the error might come from another realm.
200 `instanceof Error` is used because `isNativeError` does return `false` for some
201 things that are `instanceof Error` like the errors provided in
202 [verror](https://www.npmjs.com/package/verror) or [axios](https://axios-http.com).
203 */
204 const formatted = formatExecError(
205 error.cause,
206 config,
207 options,
208 testPath,
209 reuseMessage,
210 true
211 );
212 cause += `${prefix}${formatted}`;
213 }
214 }
215 if ('errors' in error && Array.isArray(error.errors)) {
216 for (const subError of error.errors) {
217 subErrors.push(
218 formatExecError(
219 subError,
220 config,
221 options,
222 testPath,
223 reuseMessage,
224 true
225 )
226 );
227 }
228 }
229 }
230 if (cause !== '') {
231 cause = indentAllLines(cause);
232 }
233 const separated = separateMessageFromStack(stack || '');
234 stack = separated.stack;
235 if (separated.message.includes(trim(message))) {
236 // Often stack trace already contains the duplicate of the message
237 message = separated.message;
238 }
239 message = checkForCommonEnvironmentErrors(message);
240 message = indentAllLines(message);
241 stack =
242 stack && !options.noStackTrace
243 ? `\n${formatStackTrace(stack, config, options, testPath)}`
244 : '';
245 if (
246 typeof stack !== 'string' ||
247 (blankStringRegexp.test(message) && blankStringRegexp.test(stack))
248 ) {
249 // this can happen if an empty object is thrown.
250 message = `thrown: ${(0, _prettyFormat.format)(error, {
251 maxDepth: 3
252 })}`;
253 }
254 let messageToUse;
255 if (reuseMessage || noTitle) {
256 messageToUse = ` ${message.trim()}`;
257 } else {
258 messageToUse = `${EXEC_ERROR_MESSAGE}\n\n${message}`;
259 }
260 const title = noTitle ? '' : `${TITLE_INDENT + TITLE_BULLET}`;
261 const subErrorStr =
262 subErrors.length > 0
263 ? indentAllLines(
264 `\n\nErrors contained in AggregateError:\n${subErrors.join('\n')}`
265 )
266 : '';
267 return `${title + messageToUse + stack + cause + subErrorStr}\n`;
268};
269exports.formatExecError = formatExecError;
270const removeInternalStackEntries = (lines, options) => {
271 let pathCounter = 0;
272 return lines.filter(line => {
273 if (ANONYMOUS_FN_IGNORE.test(line)) {
274 return false;
275 }
276 if (ANONYMOUS_PROMISE_IGNORE.test(line)) {
277 return false;
278 }
279 if (ANONYMOUS_GENERATOR_IGNORE.test(line)) {
280 return false;
281 }
282 if (NATIVE_NEXT_IGNORE.test(line)) {
283 return false;
284 }
285 if (nodeInternals.some(internal => internal.test(line))) {
286 return false;
287 }
288 if (!STACK_PATH_REGEXP.test(line)) {
289 return true;
290 }
291 if (JASMINE_IGNORE.test(line)) {
292 return false;
293 }
294 if (++pathCounter === 1) {
295 return true; // always keep the first line even if it's from Jest
296 }
297
298 if (options.noStackTrace) {
299 return false;
300 }
301 if (JEST_INTERNALS_IGNORE.test(line)) {
302 return false;
303 }
304 return true;
305 });
306};
307const formatPath = (line, config, relativeTestPath = null) => {
308 // Extract the file path from the trace line.
309 const match = line.match(/(^\s*at .*?\(?)([^()]+)(:[0-9]+:[0-9]+\)?.*$)/);
310 if (!match) {
311 return line;
312 }
313 let filePath = (0, _slash.default)(path.relative(config.rootDir, match[2]));
314 // highlight paths from the current test file
315 if (
316 (config.testMatch &&
317 config.testMatch.length &&
318 (0, _micromatch.default)([filePath], config.testMatch).length > 0) ||
319 filePath === relativeTestPath
320 ) {
321 filePath = _chalk.default.reset.cyan(filePath);
322 }
323 return STACK_TRACE_COLOR(match[1]) + filePath + STACK_TRACE_COLOR(match[3]);
324};
325exports.formatPath = formatPath;
326const getStackTraceLines = (
327 stack,
328 options = {
329 noCodeFrame: false,
330 noStackTrace: false
331 }
332) => removeInternalStackEntries(stack.split(/\n/), options);
333exports.getStackTraceLines = getStackTraceLines;
334const getTopFrame = lines => {
335 for (const line of lines) {
336 if (line.includes(PATH_NODE_MODULES) || line.includes(PATH_JEST_PACKAGES)) {
337 continue;
338 }
339 const parsedFrame = stackUtils.parseLine(line.trim());
340 if (parsedFrame && parsedFrame.file) {
341 if (parsedFrame.file.startsWith('file://')) {
342 parsedFrame.file = (0, _slash.default)(
343 (0, _url.fileURLToPath)(parsedFrame.file)
344 );
345 }
346 return parsedFrame;
347 }
348 }
349 return null;
350};
351exports.getTopFrame = getTopFrame;
352const formatStackTrace = (stack, config, options, testPath) => {
353 const lines = getStackTraceLines(stack, options);
354 let renderedCallsite = '';
355 const relativeTestPath = testPath
356 ? (0, _slash.default)(path.relative(config.rootDir, testPath))
357 : null;
358 if (!options.noStackTrace && !options.noCodeFrame) {
359 const topFrame = getTopFrame(lines);
360 if (topFrame) {
361 const {column, file: filename, line} = topFrame;
362 if (line && filename && path.isAbsolute(filename)) {
363 let fileContent;
364 try {
365 // TODO: check & read HasteFS instead of reading the filesystem:
366 // see: https://github.com/jestjs/jest/pull/5405#discussion_r164281696
367 fileContent = jestReadFile(filename, 'utf8');
368 renderedCallsite = getRenderedCallsite(fileContent, line, column);
369 } catch {
370 // the file does not exist or is inaccessible, we ignore
371 }
372 }
373 }
374 }
375 const stacktrace = lines
376 .filter(Boolean)
377 .map(
378 line =>
379 STACK_INDENT + formatPath(trimPaths(line), config, relativeTestPath)
380 )
381 .join('\n');
382 return renderedCallsite
383 ? `${renderedCallsite}\n${stacktrace}`
384 : `\n${stacktrace}`;
385};
386exports.formatStackTrace = formatStackTrace;
387function isErrorOrStackWithCause(errorOrStack) {
388 return (
389 typeof errorOrStack !== 'string' &&
390 'cause' in errorOrStack &&
391 (typeof errorOrStack.cause === 'string' ||
392 _util.types.isNativeError(errorOrStack.cause) ||
393 errorOrStack.cause instanceof Error)
394 );
395}
396function formatErrorStack(errorOrStack, config, options, testPath) {
397 // The stack of new Error('message') contains both the message and the stack,
398 // thus we need to sanitize and clean it for proper display using separateMessageFromStack.
399 const sourceStack =
400 typeof errorOrStack === 'string' ? errorOrStack : errorOrStack.stack || '';
401 let {message, stack} = separateMessageFromStack(sourceStack);
402 stack = options.noStackTrace
403 ? ''
404 : `${STACK_TRACE_COLOR(
405 formatStackTrace(stack, config, options, testPath)
406 )}\n`;
407 message = checkForCommonEnvironmentErrors(message);
408 message = indentAllLines(message);
409 let cause = '';
410 if (isErrorOrStackWithCause(errorOrStack)) {
411 const nestedCause = formatErrorStack(
412 errorOrStack.cause,
413 config,
414 options,
415 testPath
416 );
417 cause = `\n${MESSAGE_INDENT}Cause:\n${nestedCause}`;
418 }
419 return `${message}\n${stack}${cause}`;
420}
421function failureDetailsToErrorOrStack(failureDetails, content) {
422 if (!failureDetails) {
423 return content;
424 }
425 if (
426 _util.types.isNativeError(failureDetails) ||
427 failureDetails instanceof Error
428 ) {
429 return failureDetails; // receiving raw errors for jest-circus
430 }
431
432 if (
433 typeof failureDetails === 'object' &&
434 'error' in failureDetails &&
435 (_util.types.isNativeError(failureDetails.error) ||
436 failureDetails.error instanceof Error)
437 ) {
438 return failureDetails.error; // receiving instances of FailedAssertion for jest-jasmine
439 }
440
441 return content;
442}
443const formatResultsErrors = (testResults, config, options, testPath) => {
444 const failedResults = testResults.reduce((errors, result) => {
445 result.failureMessages.forEach((item, index) => {
446 errors.push({
447 content: item,
448 failureDetails: result.failureDetails[index],
449 result
450 });
451 });
452 return errors;
453 }, []);
454 if (!failedResults.length) {
455 return null;
456 }
457 return failedResults
458 .map(({result, content, failureDetails}) => {
459 const rootErrorOrStack = failureDetailsToErrorOrStack(
460 failureDetails,
461 content
462 );
463 const title = `${_chalk.default.bold.red(
464 TITLE_INDENT +
465 TITLE_BULLET +
466 result.ancestorTitles.join(ANCESTRY_SEPARATOR) +
467 (result.ancestorTitles.length ? ANCESTRY_SEPARATOR : '') +
468 result.title
469 )}\n`;
470 return `${title}\n${formatErrorStack(
471 rootErrorOrStack,
472 config,
473 options,
474 testPath
475 )}`;
476 })
477 .join('\n');
478};
479exports.formatResultsErrors = formatResultsErrors;
480const errorRegexp = /^Error:?\s*$/;
481const removeBlankErrorLine = str =>
482 str
483 .split('\n')
484 // Lines saying just `Error:` are useless
485 .filter(line => !errorRegexp.test(line))
486 .join('\n')
487 .trimRight();
488
489// jasmine and worker farm sometimes don't give us access to the actual
490// Error object, so we have to regexp out the message from the stack string
491// to format it.
492const separateMessageFromStack = content => {
493 if (!content) {
494 return {
495 message: '',
496 stack: ''
497 };
498 }
499
500 // All lines up to what looks like a stack -- or if nothing looks like a stack
501 // (maybe it's a code frame instead), just the first non-empty line.
502 // If the error is a plain "Error:" instead of a SyntaxError or TypeError we
503 // remove the prefix from the message because it is generally not useful.
504 const messageMatch = content.match(
505 /^(?:Error: )?([\s\S]*?(?=\n\s*at\s.*:\d*:\d*)|\s*.*)([\s\S]*)$/
506 );
507 if (!messageMatch) {
508 // For typescript
509 throw new Error('If you hit this error, the regex above is buggy.');
510 }
511 const message = removeBlankErrorLine(messageMatch[1]);
512 const stack = removeBlankErrorLine(messageMatch[2]);
513 return {
514 message,
515 stack
516 };
517};
518exports.separateMessageFromStack = separateMessageFromStack;