index.js 14 KB

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