index.js 10 KB

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