index.js 11 KB

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