index.js 9.4 KB

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