index.js 15 KB

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