index.js 16 KB

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