jestAdapterInit.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.runAndTransformResultsToJestFormat = exports.initialize = void 0;
  6. var _testResult = require('@jest/test-result');
  7. var _expect = require('expect');
  8. var _jestMessageUtil = require('jest-message-util');
  9. var _jestSnapshot = require('jest-snapshot');
  10. var _jestEach = require('jest-each');
  11. var _throat = _interopRequireDefault(require('throat'));
  12. var _state = require('../state');
  13. var _utils = require('../utils');
  14. var _run = _interopRequireDefault(require('../run'));
  15. var _testCaseReportHandler = _interopRequireDefault(
  16. require('../testCaseReportHandler')
  17. );
  18. var _ = _interopRequireDefault(require('..'));
  19. var _jestExpect = _interopRequireDefault(require('./jestExpect'));
  20. function _interopRequireDefault(obj) {
  21. return obj && obj.__esModule ? obj : {default: obj};
  22. }
  23. /**
  24. * Copyright (c) Facebook, Inc. and its affiliates. 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. const initialize = async ({
  30. config,
  31. environment,
  32. getPrettier,
  33. getBabelTraverse,
  34. globalConfig,
  35. localRequire,
  36. parentProcess,
  37. sendMessageToJest,
  38. setGlobalsForRuntime,
  39. testPath
  40. }) => {
  41. var _config$injectGlobals;
  42. if (globalConfig.testTimeout) {
  43. (0, _state.getState)().testTimeout = globalConfig.testTimeout;
  44. }
  45. const mutex = (0, _throat.default)(globalConfig.maxConcurrency); // @ts-expect-error
  46. const globalsObject = {
  47. ..._.default,
  48. fdescribe: _.default.describe.only,
  49. fit: _.default.it.only,
  50. xdescribe: _.default.describe.skip,
  51. xit: _.default.it.skip,
  52. xtest: _.default.it.skip
  53. };
  54. globalsObject.test.concurrent = (test => {
  55. const concurrent = (testName, testFn, timeout) => {
  56. // For concurrent tests we first run the function that returns promise, and then register a
  57. // normal test that will be waiting on the returned promise (when we start the test, the promise
  58. // will already be in the process of execution).
  59. // Unfortunately at this stage there's no way to know if there are any `.only` tests in the suite
  60. // that will result in this test to be skipped, so we'll be executing the promise function anyway,
  61. // even if it ends up being skipped.
  62. const promise = mutex(() => testFn());
  63. globalsObject.test(testName, () => promise, timeout);
  64. };
  65. const only = (testName, testFn, timeout) => {
  66. const promise = mutex(() => testFn()); // eslint-disable-next-line jest/no-focused-tests
  67. test.only(testName, () => promise, timeout);
  68. };
  69. concurrent.only = only;
  70. concurrent.skip = test.skip;
  71. concurrent.each = (0, _jestEach.bind)(test, false);
  72. concurrent.skip.each = (0, _jestEach.bind)(test.skip, false);
  73. only.each = (0, _jestEach.bind)(test.only, false);
  74. return concurrent;
  75. })(globalsObject.test);
  76. (0, _state.addEventHandler)(eventHandler);
  77. if (environment.handleTestEvent) {
  78. (0, _state.addEventHandler)(environment.handleTestEvent.bind(environment));
  79. }
  80. const runtimeGlobals = {
  81. ...globalsObject,
  82. expect: (0, _jestExpect.default)(globalConfig)
  83. }; // TODO: `jest-circus` might be newer than `jest-runtime` - remove `?.` for Jest 27
  84. setGlobalsForRuntime === null || setGlobalsForRuntime === void 0
  85. ? void 0
  86. : setGlobalsForRuntime(runtimeGlobals); // TODO: `jest-circus` might be newer than `jest-config` - remove `??` for Jest 27
  87. if (
  88. (_config$injectGlobals = config.injectGlobals) !== null &&
  89. _config$injectGlobals !== void 0
  90. ? _config$injectGlobals
  91. : true
  92. ) {
  93. Object.assign(environment.global, runtimeGlobals);
  94. }
  95. await (0, _state.dispatch)({
  96. name: 'setup',
  97. parentProcess,
  98. runtimeGlobals,
  99. testNamePattern: globalConfig.testNamePattern
  100. });
  101. if (config.testLocationInResults) {
  102. await (0, _state.dispatch)({
  103. name: 'include_test_location_in_result'
  104. });
  105. } // Jest tests snapshotSerializers in order preceding built-in serializers.
  106. // Therefore, add in reverse because the last added is the first tested.
  107. config.snapshotSerializers
  108. .concat()
  109. .reverse()
  110. .forEach(path => (0, _jestSnapshot.addSerializer)(localRequire(path)));
  111. const {expand, updateSnapshot} = globalConfig;
  112. const snapshotResolver = (0, _jestSnapshot.buildSnapshotResolver)(config);
  113. const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath);
  114. const snapshotState = new _jestSnapshot.SnapshotState(snapshotPath, {
  115. expand,
  116. getBabelTraverse,
  117. getPrettier,
  118. updateSnapshot
  119. }); // @ts-expect-error: snapshotState is a jest extension of `expect`
  120. (0, _expect.setState)({
  121. snapshotState,
  122. testPath
  123. });
  124. (0, _state.addEventHandler)(handleSnapshotStateAfterRetry(snapshotState));
  125. if (sendMessageToJest) {
  126. (0, _state.addEventHandler)(
  127. (0, _testCaseReportHandler.default)(testPath, sendMessageToJest)
  128. );
  129. } // Return it back to the outer scope (test runner outside the VM).
  130. return {
  131. globals: globalsObject,
  132. snapshotState
  133. };
  134. };
  135. exports.initialize = initialize;
  136. const runAndTransformResultsToJestFormat = async ({
  137. config,
  138. globalConfig,
  139. testPath
  140. }) => {
  141. const runResult = await (0, _run.default)();
  142. let numFailingTests = 0;
  143. let numPassingTests = 0;
  144. let numPendingTests = 0;
  145. let numTodoTests = 0;
  146. const assertionResults = runResult.testResults.map(testResult => {
  147. let status;
  148. if (testResult.status === 'skip') {
  149. status = 'pending';
  150. numPendingTests += 1;
  151. } else if (testResult.status === 'todo') {
  152. status = 'todo';
  153. numTodoTests += 1;
  154. } else if (testResult.errors.length) {
  155. status = 'failed';
  156. numFailingTests += 1;
  157. } else {
  158. status = 'passed';
  159. numPassingTests += 1;
  160. }
  161. const ancestorTitles = testResult.testPath.filter(
  162. name => name !== _state.ROOT_DESCRIBE_BLOCK_NAME
  163. );
  164. const title = ancestorTitles.pop();
  165. return {
  166. ancestorTitles,
  167. duration: testResult.duration,
  168. failureDetails: testResult.errorsDetailed,
  169. failureMessages: testResult.errors,
  170. fullName: title
  171. ? ancestorTitles.concat(title).join(' ')
  172. : ancestorTitles.join(' '),
  173. invocations: testResult.invocations,
  174. location: testResult.location,
  175. numPassingAsserts: 0,
  176. status,
  177. title: testResult.testPath[testResult.testPath.length - 1]
  178. };
  179. });
  180. let failureMessage = (0, _jestMessageUtil.formatResultsErrors)(
  181. assertionResults,
  182. config,
  183. globalConfig,
  184. testPath
  185. );
  186. let testExecError;
  187. if (runResult.unhandledErrors.length) {
  188. testExecError = {
  189. message: '',
  190. stack: runResult.unhandledErrors.join('\n')
  191. };
  192. failureMessage =
  193. (failureMessage || '') +
  194. '\n\n' +
  195. runResult.unhandledErrors
  196. .map(err =>
  197. (0, _jestMessageUtil.formatExecError)(err, config, globalConfig)
  198. )
  199. .join('\n');
  200. }
  201. await (0, _state.dispatch)({
  202. name: 'teardown'
  203. });
  204. return {
  205. ...(0, _testResult.createEmptyTestResult)(),
  206. console: undefined,
  207. displayName: config.displayName,
  208. failureMessage,
  209. numFailingTests,
  210. numPassingTests,
  211. numPendingTests,
  212. numTodoTests,
  213. sourceMaps: {},
  214. testExecError,
  215. testFilePath: testPath,
  216. testResults: assertionResults
  217. };
  218. };
  219. exports.runAndTransformResultsToJestFormat = runAndTransformResultsToJestFormat;
  220. const handleSnapshotStateAfterRetry = snapshotState => event => {
  221. switch (event.name) {
  222. case 'test_retry': {
  223. // Clear any snapshot data that occurred in previous test run
  224. snapshotState.clear();
  225. }
  226. }
  227. };
  228. const eventHandler = async event => {
  229. switch (event.name) {
  230. case 'test_start': {
  231. (0, _expect.setState)({
  232. currentTestName: (0, _utils.getTestID)(event.test)
  233. });
  234. break;
  235. }
  236. case 'test_done': {
  237. _addSuppressedErrors(event.test);
  238. _addExpectedAssertionErrors(event.test);
  239. break;
  240. }
  241. }
  242. };
  243. const _addExpectedAssertionErrors = test => {
  244. const failures = (0, _expect.extractExpectedAssertionsErrors)();
  245. const errors = failures.map(failure => failure.error);
  246. test.errors = test.errors.concat(errors);
  247. }; // Get suppressed errors from ``jest-matchers`` that weren't throw during
  248. // test execution and add them to the test result, potentially failing
  249. // a passing test.
  250. const _addSuppressedErrors = test => {
  251. const {suppressedErrors} = (0, _expect.getState)();
  252. (0, _expect.setState)({
  253. suppressedErrors: []
  254. });
  255. if (suppressedErrors.length) {
  256. test.errors = test.errors.concat(suppressedErrors);
  257. }
  258. };