@depup/jest-circus 30.3.0-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2049 @@
1
+ /*!
2
+ * /**
3
+ * * Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ * *
5
+ * * This source code is licensed under the MIT license found in the
6
+ * * LICENSE file in the root directory of this source tree.
7
+ * * /
8
+ */
9
+ /******/ (() => { // webpackBootstrap
10
+ /******/ "use strict";
11
+ /******/ var __webpack_modules__ = ({
12
+
13
+ /***/ "./src/eventHandler.ts"
14
+ (__unused_webpack_module, exports, __webpack_require__) {
15
+
16
+
17
+
18
+ Object.defineProperty(exports, "__esModule", ({
19
+ value: true
20
+ }));
21
+ exports["default"] = void 0;
22
+ var _jestUtil = require("jest-util");
23
+ var _globalErrorHandlers = __webpack_require__("./src/globalErrorHandlers.ts");
24
+ var _types = __webpack_require__("./src/types.ts");
25
+ var _utils = __webpack_require__("./src/utils.ts");
26
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
27
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
28
+ var jestNow = globalThis[Symbol.for('jest-native-now')] || globalThis.Date.now;
29
+ /**
30
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
31
+ *
32
+ * This source code is licensed under the MIT license found in the
33
+ * LICENSE file in the root directory of this source tree.
34
+ */
35
+ const eventHandler = (event, state) => {
36
+ switch (event.name) {
37
+ case 'include_test_location_in_result':
38
+ {
39
+ state.includeTestLocationInResult = true;
40
+ break;
41
+ }
42
+ case 'hook_start':
43
+ {
44
+ event.hook.seenDone = false;
45
+ break;
46
+ }
47
+ case 'start_describe_definition':
48
+ {
49
+ const {
50
+ blockName,
51
+ mode
52
+ } = event;
53
+ const {
54
+ currentDescribeBlock,
55
+ currentlyRunningTest
56
+ } = state;
57
+ if (currentlyRunningTest) {
58
+ currentlyRunningTest.errors.push(new Error(`Cannot nest a describe inside a test. Describe block "${blockName}" cannot run because it is nested within "${currentlyRunningTest.name}".`));
59
+ break;
60
+ }
61
+ const describeBlock = (0, _utils.makeDescribe)(blockName, currentDescribeBlock, mode);
62
+ currentDescribeBlock.children.push(describeBlock);
63
+ state.currentDescribeBlock = describeBlock;
64
+ break;
65
+ }
66
+ case 'finish_describe_definition':
67
+ {
68
+ const {
69
+ currentDescribeBlock
70
+ } = state;
71
+ (0, _jestUtil.invariant)(currentDescribeBlock, 'currentDescribeBlock must be there');
72
+ if (!(0, _utils.describeBlockHasTests)(currentDescribeBlock)) {
73
+ for (const hook of currentDescribeBlock.hooks) {
74
+ hook.asyncError.message = `Invalid: ${hook.type}() may not be used in a describe block containing no tests.`;
75
+ state.unhandledErrors.push(hook.asyncError);
76
+ }
77
+ }
78
+
79
+ // pass mode of currentDescribeBlock to tests
80
+ // but do not when there is already a single test with "only" mode
81
+ const shouldPassMode = !(currentDescribeBlock.mode === 'only' && currentDescribeBlock.children.some(child => child.type === 'test' && child.mode === 'only'));
82
+ if (shouldPassMode) {
83
+ for (const child of currentDescribeBlock.children) {
84
+ if (child.type === 'test' && !child.mode) {
85
+ child.mode = currentDescribeBlock.mode;
86
+ }
87
+ }
88
+ }
89
+ if (!state.hasFocusedTests && currentDescribeBlock.mode !== 'skip' && currentDescribeBlock.children.some(child => child.type === 'test' && child.mode === 'only')) {
90
+ state.hasFocusedTests = true;
91
+ }
92
+ if (currentDescribeBlock.parent) {
93
+ state.currentDescribeBlock = currentDescribeBlock.parent;
94
+ }
95
+ break;
96
+ }
97
+ case 'add_hook':
98
+ {
99
+ const {
100
+ currentDescribeBlock,
101
+ currentlyRunningTest,
102
+ hasStarted
103
+ } = state;
104
+ const {
105
+ asyncError,
106
+ fn,
107
+ hookType: type,
108
+ timeout
109
+ } = event;
110
+ if (currentlyRunningTest) {
111
+ currentlyRunningTest.errors.push(new Error(`Hooks cannot be defined inside tests. Hook of type "${type}" is nested within "${currentlyRunningTest.name}".`));
112
+ break;
113
+ } else if (hasStarted) {
114
+ state.unhandledErrors.push(new Error('Cannot add a hook after tests have started running. Hooks must be defined synchronously.'));
115
+ break;
116
+ }
117
+ const parent = currentDescribeBlock;
118
+ currentDescribeBlock.hooks.push({
119
+ asyncError,
120
+ fn,
121
+ parent,
122
+ seenDone: false,
123
+ timeout,
124
+ type
125
+ });
126
+ break;
127
+ }
128
+ case 'add_test':
129
+ {
130
+ const {
131
+ currentDescribeBlock,
132
+ currentlyRunningTest,
133
+ hasStarted
134
+ } = state;
135
+ const {
136
+ asyncError,
137
+ fn,
138
+ mode,
139
+ testName: name,
140
+ timeout,
141
+ concurrent,
142
+ failing
143
+ } = event;
144
+ if (currentlyRunningTest) {
145
+ currentlyRunningTest.errors.push(new Error(`Tests cannot be nested. Test "${name}" cannot run because it is nested within "${currentlyRunningTest.name}".`));
146
+ break;
147
+ } else if (hasStarted) {
148
+ state.unhandledErrors.push(new Error('Cannot add a test after tests have started running. Tests must be defined synchronously.'));
149
+ break;
150
+ }
151
+ const test = (0, _utils.makeTest)(fn, mode, concurrent, name, currentDescribeBlock, timeout, asyncError, failing);
152
+ if (currentDescribeBlock.mode !== 'skip' && test.mode === 'only') {
153
+ state.hasFocusedTests = true;
154
+ }
155
+ currentDescribeBlock.children.push(test);
156
+ currentDescribeBlock.tests.push(test);
157
+ break;
158
+ }
159
+ case 'hook_failure':
160
+ {
161
+ const {
162
+ test,
163
+ describeBlock,
164
+ error,
165
+ hook
166
+ } = event;
167
+ const {
168
+ asyncError,
169
+ type
170
+ } = hook;
171
+ if (type === 'beforeAll') {
172
+ (0, _jestUtil.invariant)(describeBlock, 'always present for `*All` hooks');
173
+ (0, _utils.addErrorToEachTestUnderDescribe)(describeBlock, error, asyncError);
174
+ } else if (type === 'afterAll') {
175
+ // Attaching `afterAll` errors to each test makes execution flow
176
+ // too complicated, so we'll consider them to be global.
177
+ state.unhandledErrors.push([error, asyncError]);
178
+ } else {
179
+ (0, _jestUtil.invariant)(test, 'always present for `*Each` hooks');
180
+ test.errors.push([error, asyncError]);
181
+ }
182
+ break;
183
+ }
184
+ case 'test_skip':
185
+ {
186
+ event.test.status = 'skip';
187
+ break;
188
+ }
189
+ case 'test_todo':
190
+ {
191
+ event.test.status = 'todo';
192
+ break;
193
+ }
194
+ case 'test_done':
195
+ {
196
+ event.test.duration = (0, _utils.getTestDuration)(event.test);
197
+ event.test.status = 'done';
198
+ state.currentlyRunningTest = null;
199
+ break;
200
+ }
201
+ case 'test_start':
202
+ {
203
+ state.currentlyRunningTest = event.test;
204
+ event.test.startedAt = jestNow();
205
+ event.test.invocations += 1;
206
+ break;
207
+ }
208
+ case 'test_fn_start':
209
+ {
210
+ event.test.seenDone = false;
211
+ break;
212
+ }
213
+ case 'test_fn_failure':
214
+ {
215
+ const {
216
+ error,
217
+ test: {
218
+ asyncError
219
+ }
220
+ } = event;
221
+ event.test.errors.push([error, asyncError]);
222
+ break;
223
+ }
224
+ case 'test_retry':
225
+ {
226
+ const logErrorsBeforeRetry = globalThis[_types.LOG_ERRORS_BEFORE_RETRY] || false;
227
+ if (logErrorsBeforeRetry) {
228
+ event.test.retryReasons.push(...event.test.errors);
229
+ }
230
+ event.test.errors = [];
231
+ break;
232
+ }
233
+ case 'run_start':
234
+ {
235
+ state.hasStarted = true;
236
+ if (globalThis[_types.TEST_TIMEOUT_SYMBOL]) {
237
+ state.testTimeout = globalThis[_types.TEST_TIMEOUT_SYMBOL];
238
+ }
239
+ break;
240
+ }
241
+ case 'run_finish':
242
+ {
243
+ break;
244
+ }
245
+ case 'setup':
246
+ {
247
+ // Uncaught exception handlers should be defined on the parent process
248
+ // object. If defined on the VM's process object they just no op and let
249
+ // the parent process crash. It might make sense to return a `dispatch`
250
+ // function to the parent process and register handlers there instead, but
251
+ // i'm not sure if this is works. For now i just replicated whatever
252
+ // jasmine was doing -- dabramov
253
+ state.parentProcess = event.parentProcess;
254
+ (0, _jestUtil.invariant)(state.parentProcess);
255
+ state.originalGlobalErrorHandlers = (0, _globalErrorHandlers.injectGlobalErrorHandlers)(state.parentProcess);
256
+ if (event.testNamePattern) {
257
+ state.testNamePattern = new RegExp(event.testNamePattern, 'i');
258
+ }
259
+ break;
260
+ }
261
+ case 'teardown':
262
+ {
263
+ (0, _jestUtil.invariant)(state.originalGlobalErrorHandlers);
264
+ (0, _jestUtil.invariant)(state.parentProcess);
265
+ (0, _globalErrorHandlers.restoreGlobalErrorHandlers)(state.parentProcess, state.originalGlobalErrorHandlers);
266
+ break;
267
+ }
268
+ case 'error':
269
+ {
270
+ // It's very likely for long-running async tests to throw errors. In this
271
+ // case we want to catch them and fail the current test. At the same time
272
+ // there's a possibility that one test sets a long timeout, that will
273
+ // eventually throw after this test finishes but during some other test
274
+ // execution, which will result in one test's error failing another test.
275
+ // In any way, it should be possible to track where the error was thrown
276
+ // from.
277
+ if (state.currentlyRunningTest) {
278
+ if (event.promise) {
279
+ state.currentlyRunningTest.unhandledRejectionErrorByPromise.set(event.promise, event.error);
280
+ } else {
281
+ state.currentlyRunningTest.errors.push(event.error);
282
+ }
283
+ } else {
284
+ if (event.promise) {
285
+ state.unhandledRejectionErrorByPromise.set(event.promise, event.error);
286
+ } else {
287
+ state.unhandledErrors.push(event.error);
288
+ }
289
+ }
290
+ break;
291
+ }
292
+ case 'error_handled':
293
+ {
294
+ if (state.currentlyRunningTest) {
295
+ state.currentlyRunningTest.unhandledRejectionErrorByPromise.delete(event.promise);
296
+ } else {
297
+ state.unhandledRejectionErrorByPromise.delete(event.promise);
298
+ }
299
+ break;
300
+ }
301
+ }
302
+ };
303
+ var _default = exports["default"] = eventHandler;
304
+
305
+ /***/ },
306
+
307
+ /***/ "./src/formatNodeAssertErrors.ts"
308
+ (__unused_webpack_module, exports) {
309
+
310
+
311
+
312
+ Object.defineProperty(exports, "__esModule", ({
313
+ value: true
314
+ }));
315
+ exports["default"] = void 0;
316
+ var _assert = require("assert");
317
+ var _chalk = _interopRequireDefault(require("chalk"));
318
+ var _jestMatcherUtils = require("jest-matcher-utils");
319
+ var _prettyFormat = require("pretty-format");
320
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
321
+ /**
322
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
323
+ *
324
+ * This source code is licensed under the MIT license found in the
325
+ * LICENSE file in the root directory of this source tree.
326
+ */
327
+
328
+ const assertOperatorsMap = {
329
+ '!=': 'notEqual',
330
+ '!==': 'notStrictEqual',
331
+ '==': 'equal',
332
+ '===': 'strictEqual'
333
+ };
334
+ const humanReadableOperators = {
335
+ deepEqual: 'to deeply equal',
336
+ deepStrictEqual: 'to deeply and strictly equal',
337
+ equal: 'to be equal',
338
+ notDeepEqual: 'not to deeply equal',
339
+ notDeepStrictEqual: 'not to deeply and strictly equal',
340
+ notEqual: 'to not be equal',
341
+ notStrictEqual: 'not be strictly equal',
342
+ strictEqual: 'to strictly be equal'
343
+ };
344
+ const formatNodeAssertErrors = (event, state) => {
345
+ if (event.name === 'test_done') {
346
+ event.test.errors = event.test.errors.map(errors => {
347
+ let error;
348
+ if (Array.isArray(errors)) {
349
+ const [originalError, asyncError] = errors;
350
+ if (originalError == null) {
351
+ error = asyncError;
352
+ } else if (originalError.stack) {
353
+ error = originalError;
354
+ } else {
355
+ error = asyncError;
356
+ error.message = originalError.message || `thrown: ${(0, _prettyFormat.format)(originalError, {
357
+ maxDepth: 3
358
+ })}`;
359
+ }
360
+ } else {
361
+ error = errors;
362
+ }
363
+ return isAssertionError(error) ? {
364
+ message: assertionErrorMessage(error, {
365
+ expand: state.expand
366
+ })
367
+ } : errors;
368
+ });
369
+ }
370
+ };
371
+ const getOperatorName = (operator, stack) => {
372
+ if (typeof operator === 'string') {
373
+ return assertOperatorsMap[operator] || operator;
374
+ }
375
+ if (stack.match('.doesNotThrow')) {
376
+ return 'doesNotThrow';
377
+ }
378
+ if (stack.match('.throws')) {
379
+ return 'throws';
380
+ }
381
+ return '';
382
+ };
383
+ const operatorMessage = operator => {
384
+ const niceOperatorName = getOperatorName(operator, '');
385
+ const humanReadableOperator = humanReadableOperators[niceOperatorName];
386
+ return typeof operator === 'string' ? `${humanReadableOperator || niceOperatorName} to:\n` : '';
387
+ };
388
+ const assertThrowingMatcherHint = operatorName => operatorName ? _chalk.default.dim('assert') + _chalk.default.dim(`.${operatorName}(`) + _chalk.default.red('function') + _chalk.default.dim(')') : '';
389
+ const assertMatcherHint = (operator, operatorName, expected) => {
390
+ let message = '';
391
+ if (operator === '==' && expected === true) {
392
+ message = _chalk.default.dim('assert') + _chalk.default.dim('(') + _chalk.default.red('received') + _chalk.default.dim(')');
393
+ } else if (operatorName) {
394
+ message = _chalk.default.dim('assert') + _chalk.default.dim(`.${operatorName}(`) + _chalk.default.red('received') + _chalk.default.dim(', ') + _chalk.default.green('expected') + _chalk.default.dim(')');
395
+ }
396
+ return message;
397
+ };
398
+ function assertionErrorMessage(error, options) {
399
+ const {
400
+ expected,
401
+ actual,
402
+ generatedMessage,
403
+ message,
404
+ operator,
405
+ stack
406
+ } = error;
407
+ const diffString = (0, _jestMatcherUtils.diff)(expected, actual, options);
408
+ const hasCustomMessage = !generatedMessage;
409
+ const operatorName = getOperatorName(operator, stack);
410
+ const trimmedStack = stack.replace(message, '').replaceAll(/AssertionError(.*)/g, '');
411
+ if (operatorName === 'doesNotThrow') {
412
+ return (
413
+ // eslint-disable-next-line prefer-template
414
+ buildHintString(assertThrowingMatcherHint(operatorName)) + _chalk.default.reset('Expected the function not to throw an error.\n') + _chalk.default.reset('Instead, it threw:\n') + ` ${(0, _jestMatcherUtils.printReceived)(actual)}` + _chalk.default.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack
415
+ );
416
+ }
417
+ if (operatorName === 'throws') {
418
+ if (error.generatedMessage) {
419
+ return buildHintString(assertThrowingMatcherHint(operatorName)) + _chalk.default.reset(error.message) + _chalk.default.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack;
420
+ }
421
+ return buildHintString(assertThrowingMatcherHint(operatorName)) + _chalk.default.reset('Expected the function to throw an error.\n') + _chalk.default.reset("But it didn't throw anything.") + _chalk.default.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + trimmedStack;
422
+ }
423
+ if (operatorName === 'fail') {
424
+ return buildHintString(assertMatcherHint(operator, operatorName, expected)) + _chalk.default.reset(hasCustomMessage ? `Message:\n ${message}` : '') + trimmedStack;
425
+ }
426
+ return (
427
+ // eslint-disable-next-line prefer-template
428
+ buildHintString(assertMatcherHint(operator, operatorName, expected)) + _chalk.default.reset(`Expected value ${operatorMessage(operator)}`) + ` ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + _chalk.default.reset('Received:\n') + ` ${(0, _jestMatcherUtils.printReceived)(actual)}` + _chalk.default.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + (diffString ? `\n\nDifference:\n\n${diffString}` : '') + trimmedStack
429
+ );
430
+ }
431
+ function isAssertionError(error) {
432
+ return error && (error instanceof _assert.AssertionError || error.name === _assert.AssertionError.name || error.code === 'ERR_ASSERTION');
433
+ }
434
+ function buildHintString(hint) {
435
+ return hint ? `${hint}\n\n` : '';
436
+ }
437
+ var _default = exports["default"] = formatNodeAssertErrors;
438
+
439
+ /***/ },
440
+
441
+ /***/ "./src/globalErrorHandlers.ts"
442
+ (__unused_webpack_module, exports, __webpack_require__) {
443
+
444
+
445
+
446
+ Object.defineProperty(exports, "__esModule", ({
447
+ value: true
448
+ }));
449
+ exports.restoreGlobalErrorHandlers = exports.injectGlobalErrorHandlers = void 0;
450
+ var _state = __webpack_require__("./src/state.ts");
451
+ /**
452
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
453
+ *
454
+ * This source code is licensed under the MIT license found in the
455
+ * LICENSE file in the root directory of this source tree.
456
+ */
457
+
458
+ const uncaughtExceptionListener = error => {
459
+ (0, _state.dispatchSync)({
460
+ error,
461
+ name: 'error'
462
+ });
463
+ };
464
+ const unhandledRejectionListener = (error, promise) => {
465
+ (0, _state.dispatchSync)({
466
+ error,
467
+ name: 'error',
468
+ promise
469
+ });
470
+ };
471
+ const rejectionHandledListener = promise => {
472
+ (0, _state.dispatchSync)({
473
+ name: 'error_handled',
474
+ promise
475
+ });
476
+ };
477
+ const injectGlobalErrorHandlers = parentProcess => {
478
+ const uncaughtException = [...process.listeners('uncaughtException')];
479
+ const unhandledRejection = [...process.listeners('unhandledRejection')];
480
+ const rejectionHandled = [...process.listeners('rejectionHandled')];
481
+ parentProcess.removeAllListeners('uncaughtException');
482
+ parentProcess.removeAllListeners('unhandledRejection');
483
+ parentProcess.removeAllListeners('rejectionHandled');
484
+ parentProcess.on('uncaughtException', uncaughtExceptionListener);
485
+ parentProcess.on('unhandledRejection', unhandledRejectionListener);
486
+ parentProcess.on('rejectionHandled', rejectionHandledListener);
487
+ return {
488
+ rejectionHandled,
489
+ uncaughtException,
490
+ unhandledRejection
491
+ };
492
+ };
493
+ exports.injectGlobalErrorHandlers = injectGlobalErrorHandlers;
494
+ const restoreGlobalErrorHandlers = (parentProcess, originalErrorHandlers) => {
495
+ parentProcess.removeListener('uncaughtException', uncaughtExceptionListener);
496
+ parentProcess.removeListener('unhandledRejection', unhandledRejectionListener);
497
+ parentProcess.removeListener('rejectionHandled', rejectionHandledListener);
498
+ for (const listener of originalErrorHandlers.uncaughtException) {
499
+ parentProcess.on('uncaughtException', listener);
500
+ }
501
+ for (const listener of originalErrorHandlers.unhandledRejection) {
502
+ parentProcess.on('unhandledRejection', listener);
503
+ }
504
+ for (const listener of originalErrorHandlers.rejectionHandled) {
505
+ parentProcess.on('rejectionHandled', listener);
506
+ }
507
+ };
508
+ exports.restoreGlobalErrorHandlers = restoreGlobalErrorHandlers;
509
+
510
+ /***/ },
511
+
512
+ /***/ "./src/index.ts"
513
+ (__unused_webpack_module, exports, __webpack_require__) {
514
+
515
+
516
+
517
+ Object.defineProperty(exports, "__esModule", ({
518
+ value: true
519
+ }));
520
+ Object.defineProperty(exports, "addEventHandler", ({
521
+ enumerable: true,
522
+ get: function () {
523
+ return _state.addEventHandler;
524
+ }
525
+ }));
526
+ exports.describe = exports["default"] = exports.beforeEach = exports.beforeAll = exports.afterEach = exports.afterAll = void 0;
527
+ Object.defineProperty(exports, "getState", ({
528
+ enumerable: true,
529
+ get: function () {
530
+ return _state.getState;
531
+ }
532
+ }));
533
+ exports.it = void 0;
534
+ Object.defineProperty(exports, "removeEventHandler", ({
535
+ enumerable: true,
536
+ get: function () {
537
+ return _state.removeEventHandler;
538
+ }
539
+ }));
540
+ Object.defineProperty(exports, "resetState", ({
541
+ enumerable: true,
542
+ get: function () {
543
+ return _state.resetState;
544
+ }
545
+ }));
546
+ Object.defineProperty(exports, "run", ({
547
+ enumerable: true,
548
+ get: function () {
549
+ return _run.default;
550
+ }
551
+ }));
552
+ Object.defineProperty(exports, "setState", ({
553
+ enumerable: true,
554
+ get: function () {
555
+ return _state.setState;
556
+ }
557
+ }));
558
+ exports.test = void 0;
559
+ var _jestEach = require("jest-each");
560
+ var _jestUtil = require("jest-util");
561
+ var _state = __webpack_require__("./src/state.ts");
562
+ var _run = _interopRequireDefault(__webpack_require__("./src/run.ts"));
563
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
564
+ /**
565
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
566
+ *
567
+ * This source code is licensed under the MIT license found in the
568
+ * LICENSE file in the root directory of this source tree.
569
+ */
570
+
571
+ const describe = exports.describe = (() => {
572
+ const describe = (blockName, blockFn) => _dispatchDescribe(blockFn, blockName, describe);
573
+ const only = (blockName, blockFn) => _dispatchDescribe(blockFn, blockName, only, 'only');
574
+ const skip = (blockName, blockFn) => _dispatchDescribe(blockFn, blockName, skip, 'skip');
575
+ describe.each = (0, _jestEach.bind)(describe, false);
576
+ only.each = (0, _jestEach.bind)(only, false);
577
+ skip.each = (0, _jestEach.bind)(skip, false);
578
+ describe.only = only;
579
+ describe.skip = skip;
580
+ return describe;
581
+ })();
582
+ const _dispatchDescribe = (blockFn, blockName, describeFn, mode) => {
583
+ const asyncError = new _jestUtil.ErrorWithStack(undefined, describeFn);
584
+ if (blockFn === undefined) {
585
+ asyncError.message = 'Missing second argument. It must be a callback function.';
586
+ throw asyncError;
587
+ }
588
+ if (typeof blockFn !== 'function') {
589
+ asyncError.message = `Invalid second argument, ${blockFn}. It must be a callback function.`;
590
+ throw asyncError;
591
+ }
592
+ try {
593
+ blockName = (0, _jestUtil.convertDescriptorToString)(blockName);
594
+ } catch (error) {
595
+ asyncError.message = error.message;
596
+ throw asyncError;
597
+ }
598
+ (0, _state.dispatchSync)({
599
+ asyncError,
600
+ blockName,
601
+ mode,
602
+ name: 'start_describe_definition'
603
+ });
604
+ const describeReturn = blockFn();
605
+ if ((0, _jestUtil.isPromise)(describeReturn)) {
606
+ throw new _jestUtil.ErrorWithStack('Returning a Promise from "describe" is not supported. Tests must be defined synchronously.', describeFn);
607
+ } else if (describeReturn !== undefined) {
608
+ throw new _jestUtil.ErrorWithStack('A "describe" callback must not return a value.', describeFn);
609
+ }
610
+ (0, _state.dispatchSync)({
611
+ blockName,
612
+ mode,
613
+ name: 'finish_describe_definition'
614
+ });
615
+ };
616
+ const _addHook = (fn, hookType, hookFn, timeout) => {
617
+ const asyncError = new _jestUtil.ErrorWithStack(undefined, hookFn);
618
+ if (typeof fn !== 'function') {
619
+ asyncError.message = 'Invalid first argument. It must be a callback function.';
620
+ throw asyncError;
621
+ }
622
+ (0, _state.dispatchSync)({
623
+ asyncError,
624
+ fn,
625
+ hookType,
626
+ name: 'add_hook',
627
+ timeout
628
+ });
629
+ };
630
+
631
+ // Hooks have to pass themselves to the HOF in order for us to trim stack traces.
632
+ const beforeEach = (fn, timeout) => _addHook(fn, 'beforeEach', beforeEach, timeout);
633
+ exports.beforeEach = beforeEach;
634
+ const beforeAll = (fn, timeout) => _addHook(fn, 'beforeAll', beforeAll, timeout);
635
+ exports.beforeAll = beforeAll;
636
+ const afterEach = (fn, timeout) => _addHook(fn, 'afterEach', afterEach, timeout);
637
+ exports.afterEach = afterEach;
638
+ const afterAll = (fn, timeout) => _addHook(fn, 'afterAll', afterAll, timeout);
639
+ exports.afterAll = afterAll;
640
+ const test = exports.test = (() => {
641
+ const test = (testName, fn, timeout) => _addTest(testName, undefined, false, fn, test, timeout);
642
+ const skip = (testName, fn, timeout) => _addTest(testName, 'skip', false, fn, skip, timeout);
643
+ const only = (testName, fn, timeout) => _addTest(testName, 'only', false, fn, test.only, timeout);
644
+ const concurrentTest = (testName, fn, timeout) => _addTest(testName, undefined, true, fn, concurrentTest, timeout);
645
+ const concurrentOnly = (testName, fn, timeout) => _addTest(testName, 'only', true, fn, concurrentOnly, timeout);
646
+ const bindFailing = (concurrent, mode) => {
647
+ const failing = (testName, fn, timeout, eachError) => _addTest(testName, mode, concurrent, fn, failing, timeout, true, eachError);
648
+ failing.each = (0, _jestEach.bind)(failing, false, true);
649
+ return failing;
650
+ };
651
+ test.todo = (testName, ...rest) => {
652
+ if (rest.length > 0 || typeof testName !== 'string') {
653
+ throw new _jestUtil.ErrorWithStack('Todo must be called with only a description.', test.todo);
654
+ }
655
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
656
+ return _addTest(testName, 'todo', false, () => {}, test.todo);
657
+ };
658
+ const _addTest = (testName, mode, concurrent, fn, testFn, timeout, failing, asyncError = new _jestUtil.ErrorWithStack(undefined, testFn)) => {
659
+ try {
660
+ testName = (0, _jestUtil.convertDescriptorToString)(testName);
661
+ } catch (error) {
662
+ asyncError.message = error.message;
663
+ throw asyncError;
664
+ }
665
+ if (fn === undefined) {
666
+ asyncError.message = 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.';
667
+ throw asyncError;
668
+ }
669
+ if (typeof fn !== 'function') {
670
+ asyncError.message = `Invalid second argument, ${fn}. It must be a callback function.`;
671
+ throw asyncError;
672
+ }
673
+ return (0, _state.dispatchSync)({
674
+ asyncError,
675
+ concurrent,
676
+ failing: failing === undefined ? false : failing,
677
+ fn,
678
+ mode,
679
+ name: 'add_test',
680
+ testName,
681
+ timeout
682
+ });
683
+ };
684
+ test.each = (0, _jestEach.bind)(test);
685
+ only.each = (0, _jestEach.bind)(only);
686
+ skip.each = (0, _jestEach.bind)(skip);
687
+ concurrentTest.each = (0, _jestEach.bind)(concurrentTest, false);
688
+ concurrentOnly.each = (0, _jestEach.bind)(concurrentOnly, false);
689
+ only.failing = bindFailing(false, 'only');
690
+ skip.failing = bindFailing(false, 'skip');
691
+ test.failing = bindFailing(false);
692
+ test.only = only;
693
+ test.skip = skip;
694
+ test.concurrent = concurrentTest;
695
+ concurrentTest.only = concurrentOnly;
696
+ concurrentTest.skip = skip;
697
+ concurrentTest.failing = bindFailing(true);
698
+ concurrentOnly.failing = bindFailing(true, 'only');
699
+ return test;
700
+ })();
701
+ const it = exports.it = test;
702
+ var _default = exports["default"] = {
703
+ afterAll,
704
+ afterEach,
705
+ beforeAll,
706
+ beforeEach,
707
+ describe,
708
+ it,
709
+ test
710
+ };
711
+
712
+ /***/ },
713
+
714
+ /***/ "./src/run.ts"
715
+ (__unused_webpack_module, exports, __webpack_require__) {
716
+
717
+
718
+
719
+ Object.defineProperty(exports, "__esModule", ({
720
+ value: true
721
+ }));
722
+ exports["default"] = void 0;
723
+ var _async_hooks = require("async_hooks");
724
+ var _pLimit = _interopRequireDefault(require("p-limit"));
725
+ var _expect = require("@jest/expect");
726
+ var _jestUtil = require("jest-util");
727
+ var _shuffleArray = _interopRequireWildcard(__webpack_require__("./src/shuffleArray.ts"));
728
+ var _state = __webpack_require__("./src/state.ts");
729
+ var _types = __webpack_require__("./src/types.ts");
730
+ var _utils = __webpack_require__("./src/utils.ts");
731
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
732
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
733
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
734
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
735
+ var Promise = globalThis[Symbol.for('jest-native-promise')] || globalThis.Promise;
736
+ /**
737
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
738
+ *
739
+ * This source code is licensed under the MIT license found in the
740
+ * LICENSE file in the root directory of this source tree.
741
+ */
742
+ // Global values can be overwritten by mocks or tests. We'll capture
743
+ // the original values in the variables before we require any files.
744
+ const {
745
+ setTimeout
746
+ } = globalThis;
747
+ const testNameStorage = new _async_hooks.AsyncLocalStorage();
748
+ const run = async () => {
749
+ const {
750
+ rootDescribeBlock,
751
+ seed,
752
+ randomize
753
+ } = (0, _state.getState)();
754
+ _expect.jestExpect.setState({
755
+ currentConcurrentTestName: () => testNameStorage.getStore()
756
+ });
757
+ const rng = randomize ? (0, _shuffleArray.rngBuilder)(seed) : undefined;
758
+ await (0, _state.dispatch)({
759
+ name: 'run_start'
760
+ });
761
+ await _runTestsForDescribeBlock(rootDescribeBlock, rng);
762
+ await (0, _state.dispatch)({
763
+ name: 'run_finish'
764
+ });
765
+ return (0, _utils.makeRunResult)((0, _state.getState)().rootDescribeBlock, (0, _state.getState)().unhandledErrors);
766
+ };
767
+ function* regroupConcurrentChildren(children) {
768
+ const concurrentTests = children.filter(child => child.type === 'test' && child.concurrent);
769
+ if (concurrentTests.length === 0) {
770
+ yield* children;
771
+ return;
772
+ }
773
+ let collectedConcurrent = false;
774
+ for (const child of children) {
775
+ if (child.type === 'test' && child.concurrent) {
776
+ if (!collectedConcurrent) {
777
+ collectedConcurrent = true;
778
+ yield {
779
+ tests: concurrentTests,
780
+ type: 'test-concurrent'
781
+ };
782
+ }
783
+ } else {
784
+ yield child;
785
+ }
786
+ }
787
+ }
788
+ const _runTestsForDescribeBlock = async (describeBlock, rng) => {
789
+ await (0, _state.dispatch)({
790
+ describeBlock,
791
+ name: 'run_describe_start'
792
+ });
793
+ const {
794
+ beforeAll,
795
+ afterAll
796
+ } = (0, _utils.getAllHooksForDescribe)(describeBlock);
797
+ const isSkipped = describeBlock.mode === 'skip';
798
+ if (!isSkipped) {
799
+ for (const hook of beforeAll) {
800
+ await _callCircusHook({
801
+ describeBlock,
802
+ hook
803
+ });
804
+ }
805
+ }
806
+
807
+ // Tests that fail and are retried we run after other tests
808
+ const retryTimes = Number.parseInt(globalThis[_types.RETRY_TIMES], 10) || 0;
809
+ const hasRetryTimes = retryTimes > 0;
810
+ const waitBeforeRetry = Number.parseInt(globalThis[_types.WAIT_BEFORE_RETRY], 10) || 0;
811
+ const retryImmediately = globalThis[_types.RETRY_IMMEDIATELY] || false;
812
+ const deferredRetryTests = [];
813
+ if (rng) {
814
+ describeBlock.children = (0, _shuffleArray.default)(describeBlock.children, rng);
815
+ }
816
+ // Regroup concurrent tests as a single "sequential" unit
817
+ const children = regroupConcurrentChildren(describeBlock.children);
818
+ const rerunTest = async test => {
819
+ let numRetriesAvailable = retryTimes;
820
+ while (numRetriesAvailable > 0 && test.errors.length > 0) {
821
+ // Clear errors so retries occur
822
+ await (0, _state.dispatch)({
823
+ name: 'test_retry',
824
+ test
825
+ });
826
+ if (waitBeforeRetry > 0) {
827
+ await new Promise(resolve => setTimeout(resolve, waitBeforeRetry));
828
+ }
829
+ await _runTest(test, isSkipped);
830
+ numRetriesAvailable--;
831
+ }
832
+ };
833
+ const handleRetry = async (test, hasErrorsBeforeTestRun, hasRetryTimes) => {
834
+ // no retry if the test passed or had errors before the test ran
835
+ if (test.errors.length === 0 || hasErrorsBeforeTestRun || !hasRetryTimes) {
836
+ return;
837
+ }
838
+ if (!retryImmediately) {
839
+ deferredRetryTests.push(test);
840
+ return;
841
+ }
842
+
843
+ // If immediate retry is set, we retry the test immediately after the first run
844
+ await rerunTest(test);
845
+ };
846
+ const runTestWithContext = async child => {
847
+ const hasErrorsBeforeTestRun = child.errors.length > 0;
848
+ return testNameStorage.run((0, _utils.getTestID)(child), async () => {
849
+ await _runTest(child, isSkipped);
850
+ await handleRetry(child, hasErrorsBeforeTestRun, hasRetryTimes);
851
+ });
852
+ };
853
+ for (const child of children) {
854
+ switch (child.type) {
855
+ case 'describeBlock':
856
+ {
857
+ await _runTestsForDescribeBlock(child, rng);
858
+ break;
859
+ }
860
+ case 'test':
861
+ {
862
+ await runTestWithContext(child);
863
+ break;
864
+ }
865
+ case 'test-concurrent':
866
+ {
867
+ await (0, _state.dispatch)({
868
+ describeBlock,
869
+ name: 'concurrent_tests_start',
870
+ tests: child.tests
871
+ });
872
+ const concurrencyLimiter = (0, _pLimit.default)((0, _state.getState)().maxConcurrency);
873
+ const tasks = child.tests.map(concurrentTest => concurrencyLimiter(() => runTestWithContext(concurrentTest)));
874
+ await Promise.all(tasks);
875
+ await (0, _state.dispatch)({
876
+ describeBlock,
877
+ name: 'concurrent_tests_end',
878
+ tests: child.tests
879
+ });
880
+ break;
881
+ }
882
+ }
883
+ }
884
+
885
+ // Re-run failed tests n-times if configured
886
+ for (const test of deferredRetryTests) {
887
+ await rerunTest(test);
888
+ }
889
+ if (!isSkipped) {
890
+ for (const hook of afterAll) {
891
+ await _callCircusHook({
892
+ describeBlock,
893
+ hook
894
+ });
895
+ }
896
+ }
897
+ await (0, _state.dispatch)({
898
+ describeBlock,
899
+ name: 'run_describe_finish'
900
+ });
901
+ };
902
+ const _runTest = async (test, parentSkipped) => {
903
+ await (0, _state.dispatch)({
904
+ name: 'test_start',
905
+ test
906
+ });
907
+ const testContext = Object.create(null);
908
+ const {
909
+ hasFocusedTests,
910
+ testNamePattern
911
+ } = (0, _state.getState)();
912
+ const isSkipped = parentSkipped || test.mode === 'skip' || hasFocusedTests && test.mode === undefined || testNamePattern && !testNamePattern.test((0, _utils.getTestID)(test));
913
+ if (isSkipped) {
914
+ await (0, _state.dispatch)({
915
+ name: 'test_skip',
916
+ test
917
+ });
918
+ return;
919
+ }
920
+ if (test.mode === 'todo') {
921
+ await (0, _state.dispatch)({
922
+ name: 'test_todo',
923
+ test
924
+ });
925
+ return;
926
+ }
927
+ await (0, _state.dispatch)({
928
+ name: 'test_started',
929
+ test
930
+ });
931
+ const {
932
+ afterEach,
933
+ beforeEach
934
+ } = (0, _utils.getEachHooksForTest)(test);
935
+ for (const hook of beforeEach) {
936
+ if (test.errors.length > 0) {
937
+ // If any of the before hooks failed already, we don't run any
938
+ // hooks after that.
939
+ break;
940
+ }
941
+ await _callCircusHook({
942
+ hook,
943
+ test,
944
+ testContext
945
+ });
946
+ }
947
+ await _callCircusTest(test, testContext);
948
+ for (const hook of afterEach) {
949
+ await _callCircusHook({
950
+ hook,
951
+ test,
952
+ testContext
953
+ });
954
+ }
955
+
956
+ // `afterAll` hooks should not affect test status (pass or fail), because if
957
+ // we had a global `afterAll` hook it would block all existing tests until
958
+ // this hook is executed. So we dispatch `test_done` right away.
959
+ await (0, _state.dispatch)({
960
+ name: 'test_done',
961
+ test
962
+ });
963
+ };
964
+ const _callCircusHook = async ({
965
+ hook,
966
+ test,
967
+ describeBlock,
968
+ testContext = {}
969
+ }) => {
970
+ await (0, _state.dispatch)({
971
+ hook,
972
+ name: 'hook_start'
973
+ });
974
+ const timeout = hook.timeout || (0, _state.getState)().testTimeout;
975
+ try {
976
+ await (0, _utils.callAsyncCircusFn)(hook, testContext, {
977
+ isHook: true,
978
+ timeout
979
+ });
980
+ await (0, _state.dispatch)({
981
+ describeBlock,
982
+ hook,
983
+ name: 'hook_success',
984
+ test
985
+ });
986
+ } catch (error) {
987
+ await (0, _state.dispatch)({
988
+ describeBlock,
989
+ error,
990
+ hook,
991
+ name: 'hook_failure',
992
+ test
993
+ });
994
+ }
995
+ };
996
+ const _callCircusTest = async (test, testContext) => {
997
+ await (0, _state.dispatch)({
998
+ name: 'test_fn_start',
999
+ test
1000
+ });
1001
+ const timeout = test.timeout || (0, _state.getState)().testTimeout;
1002
+ (0, _jestUtil.invariant)(test.fn, "Tests with no 'fn' should have 'mode' set to 'skipped'");
1003
+ if (test.errors.length > 0) {
1004
+ return; // We don't run the test if there's already an error in before hooks.
1005
+ }
1006
+ try {
1007
+ await (0, _utils.callAsyncCircusFn)(test, testContext, {
1008
+ isHook: false,
1009
+ timeout
1010
+ });
1011
+ if (test.failing) {
1012
+ test.asyncError.message = 'Failing test passed even though it was supposed to fail. Remove `.failing` to remove error.';
1013
+ await (0, _state.dispatch)({
1014
+ error: test.asyncError,
1015
+ name: 'test_fn_failure',
1016
+ test
1017
+ });
1018
+ } else {
1019
+ await (0, _state.dispatch)({
1020
+ name: 'test_fn_success',
1021
+ test
1022
+ });
1023
+ }
1024
+ } catch (error) {
1025
+ if (test.failing) {
1026
+ await (0, _state.dispatch)({
1027
+ name: 'test_fn_success',
1028
+ test
1029
+ });
1030
+ } else {
1031
+ await (0, _state.dispatch)({
1032
+ error,
1033
+ name: 'test_fn_failure',
1034
+ test
1035
+ });
1036
+ }
1037
+ }
1038
+ };
1039
+ var _default = exports["default"] = run;
1040
+
1041
+ /***/ },
1042
+
1043
+ /***/ "./src/shuffleArray.ts"
1044
+ (__unused_webpack_module, exports) {
1045
+
1046
+
1047
+
1048
+ Object.defineProperty(exports, "__esModule", ({
1049
+ value: true
1050
+ }));
1051
+ exports["default"] = shuffleArray;
1052
+ exports.rngBuilder = void 0;
1053
+ var _pureRand = require("pure-rand");
1054
+ /**
1055
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1056
+ *
1057
+ * This source code is licensed under the MIT license found in the
1058
+ * LICENSE file in the root directory of this source tree.
1059
+ */
1060
+
1061
+ // Generates [from, to] inclusive
1062
+
1063
+ const rngBuilder = seed => {
1064
+ const gen = (0, _pureRand.xoroshiro128plus)(seed);
1065
+ return {
1066
+ next: (from, to) => (0, _pureRand.unsafeUniformIntDistribution)(from, to, gen)
1067
+ };
1068
+ };
1069
+
1070
+ // Fisher-Yates shuffle
1071
+ // This is performed in-place
1072
+ exports.rngBuilder = rngBuilder;
1073
+ function shuffleArray(array, random) {
1074
+ const length = array.length;
1075
+ if (length === 0) {
1076
+ return [];
1077
+ }
1078
+ for (let i = 0; i < length; i++) {
1079
+ const n = random.next(i, length - 1);
1080
+ const value = array[i];
1081
+ array[i] = array[n];
1082
+ array[n] = value;
1083
+ }
1084
+ return array;
1085
+ }
1086
+
1087
+ /***/ },
1088
+
1089
+ /***/ "./src/state.ts"
1090
+ (__unused_webpack_module, exports, __webpack_require__) {
1091
+
1092
+
1093
+
1094
+ Object.defineProperty(exports, "__esModule", ({
1095
+ value: true
1096
+ }));
1097
+ exports.setState = exports.resetState = exports.removeEventHandler = exports.getState = exports.dispatchSync = exports.dispatch = exports.addEventHandler = exports.ROOT_DESCRIBE_BLOCK_NAME = void 0;
1098
+ var _jestUtil = require("jest-util");
1099
+ var _eventHandler = _interopRequireDefault(__webpack_require__("./src/eventHandler.ts"));
1100
+ var _formatNodeAssertErrors = _interopRequireDefault(__webpack_require__("./src/formatNodeAssertErrors.ts"));
1101
+ var _types = __webpack_require__("./src/types.ts");
1102
+ var _utils = __webpack_require__("./src/utils.ts");
1103
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1104
+ /**
1105
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1106
+ *
1107
+ * This source code is licensed under the MIT license found in the
1108
+ * LICENSE file in the root directory of this source tree.
1109
+ */
1110
+
1111
+ const handlers = globalThis[_types.EVENT_HANDLERS] || [_eventHandler.default, _formatNodeAssertErrors.default];
1112
+ (0, _jestUtil.setGlobal)(globalThis, _types.EVENT_HANDLERS, handlers, 'retain');
1113
+ const ROOT_DESCRIBE_BLOCK_NAME = exports.ROOT_DESCRIBE_BLOCK_NAME = 'ROOT_DESCRIBE_BLOCK';
1114
+ const createState = () => {
1115
+ const ROOT_DESCRIBE_BLOCK = (0, _utils.makeDescribe)(ROOT_DESCRIBE_BLOCK_NAME);
1116
+ return {
1117
+ currentDescribeBlock: ROOT_DESCRIBE_BLOCK,
1118
+ currentlyRunningTest: null,
1119
+ expand: undefined,
1120
+ hasFocusedTests: false,
1121
+ hasStarted: false,
1122
+ includeTestLocationInResult: false,
1123
+ maxConcurrency: 5,
1124
+ parentProcess: null,
1125
+ rootDescribeBlock: ROOT_DESCRIBE_BLOCK,
1126
+ seed: 0,
1127
+ testNamePattern: null,
1128
+ testTimeout: 5000,
1129
+ unhandledErrors: [],
1130
+ unhandledRejectionErrorByPromise: new Map()
1131
+ };
1132
+ };
1133
+ const getState = () => globalThis[_types.STATE_SYM];
1134
+ exports.getState = getState;
1135
+ const setState = state => {
1136
+ (0, _jestUtil.setGlobal)(globalThis, _types.STATE_SYM, state);
1137
+ (0, _jestUtil.protectProperties)(state, ['hasFocusedTests', 'hasStarted', 'includeTestLocationInResult', 'maxConcurrency', 'seed', 'testNamePattern', 'testTimeout', 'unhandledErrors', 'unhandledRejectionErrorByPromise']);
1138
+ return state;
1139
+ };
1140
+ exports.setState = setState;
1141
+ const resetState = () => {
1142
+ setState(createState());
1143
+ };
1144
+ exports.resetState = resetState;
1145
+ resetState();
1146
+ const dispatch = async event => {
1147
+ for (const handler of handlers) {
1148
+ await handler(event, getState());
1149
+ }
1150
+ };
1151
+ exports.dispatch = dispatch;
1152
+ const dispatchSync = event => {
1153
+ for (const handler of handlers) {
1154
+ handler(event, getState());
1155
+ }
1156
+ };
1157
+ exports.dispatchSync = dispatchSync;
1158
+ const addEventHandler = handler => {
1159
+ handlers.push(handler);
1160
+ };
1161
+ exports.addEventHandler = addEventHandler;
1162
+ const removeEventHandler = handler => {
1163
+ const index = handlers.lastIndexOf(handler);
1164
+ if (index !== -1) {
1165
+ handlers.splice(index, 1);
1166
+ }
1167
+ };
1168
+ exports.removeEventHandler = removeEventHandler;
1169
+
1170
+ /***/ },
1171
+
1172
+ /***/ "./src/testCaseReportHandler.ts"
1173
+ (__unused_webpack_module, exports, __webpack_require__) {
1174
+
1175
+
1176
+
1177
+ Object.defineProperty(exports, "__esModule", ({
1178
+ value: true
1179
+ }));
1180
+ exports["default"] = void 0;
1181
+ var _utils = __webpack_require__("./src/utils.ts");
1182
+ /**
1183
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1184
+ *
1185
+ * This source code is licensed under the MIT license found in the
1186
+ * LICENSE file in the root directory of this source tree.
1187
+ */
1188
+
1189
+ const testCaseReportHandler = (testPath, sendMessageToJest) => event => {
1190
+ switch (event.name) {
1191
+ case 'test_started':
1192
+ {
1193
+ const testCaseStartInfo = (0, _utils.createTestCaseStartInfo)(event.test);
1194
+ sendMessageToJest('test-case-start', [testPath, testCaseStartInfo]);
1195
+ break;
1196
+ }
1197
+ case 'test_todo':
1198
+ case 'test_done':
1199
+ {
1200
+ const testResult = (0, _utils.makeSingleTestResult)(event.test);
1201
+ const testCaseResult = (0, _utils.parseSingleTestResult)(testResult);
1202
+ sendMessageToJest('test-case-result', [testPath, testCaseResult]);
1203
+ break;
1204
+ }
1205
+ }
1206
+ };
1207
+ var _default = exports["default"] = testCaseReportHandler;
1208
+
1209
+ /***/ },
1210
+
1211
+ /***/ "./src/types.ts"
1212
+ (__unused_webpack_module, exports) {
1213
+
1214
+
1215
+
1216
+ Object.defineProperty(exports, "__esModule", ({
1217
+ value: true
1218
+ }));
1219
+ exports.WAIT_BEFORE_RETRY = exports.TEST_TIMEOUT_SYMBOL = exports.STATE_SYM = exports.RETRY_TIMES = exports.RETRY_IMMEDIATELY = exports.LOG_ERRORS_BEFORE_RETRY = exports.EVENT_HANDLERS = void 0;
1220
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
1221
+ /**
1222
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1223
+ *
1224
+ * This source code is licensed under the MIT license found in the
1225
+ * LICENSE file in the root directory of this source tree.
1226
+ */
1227
+
1228
+ const STATE_SYM = exports.STATE_SYM = Symbol('JEST_STATE_SYMBOL');
1229
+ const RETRY_TIMES = exports.RETRY_TIMES = Symbol.for('RETRY_TIMES');
1230
+ const RETRY_IMMEDIATELY = exports.RETRY_IMMEDIATELY = Symbol.for('RETRY_IMMEDIATELY');
1231
+ const WAIT_BEFORE_RETRY = exports.WAIT_BEFORE_RETRY = Symbol.for('WAIT_BEFORE_RETRY');
1232
+ // To pass this value from Runtime object to state we need to use global[sym]
1233
+ const TEST_TIMEOUT_SYMBOL = exports.TEST_TIMEOUT_SYMBOL = Symbol.for('TEST_TIMEOUT_SYMBOL');
1234
+ const EVENT_HANDLERS = exports.EVENT_HANDLERS = Symbol.for('EVENT_HANDLERS');
1235
+ const LOG_ERRORS_BEFORE_RETRY = exports.LOG_ERRORS_BEFORE_RETRY = Symbol.for('LOG_ERRORS_BEFORE_RETRY');
1236
+
1237
+ /***/ },
1238
+
1239
+ /***/ "./src/unhandledRejectionHandler.ts"
1240
+ (__unused_webpack_module, exports, __webpack_require__) {
1241
+
1242
+
1243
+
1244
+ Object.defineProperty(exports, "__esModule", ({
1245
+ value: true
1246
+ }));
1247
+ exports.unhandledRejectionHandler = void 0;
1248
+ var _jestUtil = require("jest-util");
1249
+ var _utils = __webpack_require__("./src/utils.ts");
1250
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
1251
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
1252
+ var Promise = globalThis[Symbol.for('jest-native-promise')] || globalThis.Promise;
1253
+ /**
1254
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1255
+ *
1256
+ * This source code is licensed under the MIT license found in the
1257
+ * LICENSE file in the root directory of this source tree.
1258
+ */
1259
+ // Global values can be overwritten by mocks or tests. We'll capture
1260
+ // the original values in the variables before we require any files.
1261
+ const {
1262
+ setTimeout
1263
+ } = globalThis;
1264
+ const untilNextEventLoopTurn = async () => {
1265
+ return new Promise(resolve => {
1266
+ setTimeout(resolve, 0);
1267
+ });
1268
+ };
1269
+ const unhandledRejectionHandler = (runtime, waitForUnhandledRejections) => {
1270
+ return async (event, state) => {
1271
+ if (event.name === 'hook_start') {
1272
+ runtime.enterTestCode();
1273
+ } else if (event.name === 'hook_success' || event.name === 'hook_failure') {
1274
+ runtime.leaveTestCode();
1275
+ if (waitForUnhandledRejections) {
1276
+ // We need to give event loop the time to actually execute `rejectionHandled`, `uncaughtException` or `unhandledRejection` events
1277
+ await untilNextEventLoopTurn();
1278
+ }
1279
+ const {
1280
+ test,
1281
+ describeBlock,
1282
+ hook
1283
+ } = event;
1284
+ const {
1285
+ asyncError,
1286
+ type
1287
+ } = hook;
1288
+ if (type === 'beforeAll') {
1289
+ (0, _jestUtil.invariant)(describeBlock, 'always present for `*All` hooks');
1290
+ for (const error of state.unhandledRejectionErrorByPromise.values()) {
1291
+ (0, _utils.addErrorToEachTestUnderDescribe)(describeBlock, error, asyncError);
1292
+ }
1293
+ } else if (type === 'afterAll') {
1294
+ // Attaching `afterAll` errors to each test makes execution flow
1295
+ // too complicated, so we'll consider them to be global.
1296
+ for (const error of state.unhandledRejectionErrorByPromise.values()) {
1297
+ state.unhandledErrors.push([error, asyncError]);
1298
+ }
1299
+ } else {
1300
+ (0, _jestUtil.invariant)(test, 'always present for `*Each` hooks');
1301
+ for (const error of test.unhandledRejectionErrorByPromise.values()) {
1302
+ test.errors.push([error, asyncError]);
1303
+ }
1304
+ }
1305
+ } else if (event.name === 'test_fn_start') {
1306
+ runtime.enterTestCode();
1307
+ } else if (event.name === 'test_fn_success' || event.name === 'test_fn_failure') {
1308
+ runtime.leaveTestCode();
1309
+ if (waitForUnhandledRejections) {
1310
+ // We need to give event loop the time to actually execute `rejectionHandled`, `uncaughtException` or `unhandledRejection` events
1311
+ await untilNextEventLoopTurn();
1312
+ }
1313
+ const {
1314
+ test
1315
+ } = event;
1316
+ (0, _jestUtil.invariant)(test, 'always present for `*Each` hooks');
1317
+ for (const error of test.unhandledRejectionErrorByPromise.values()) {
1318
+ test.errors.push([error, event.test.asyncError]);
1319
+ }
1320
+ } else if (event.name === 'teardown') {
1321
+ if (waitForUnhandledRejections) {
1322
+ // We need to give event loop the time to actually execute `rejectionHandled`, `uncaughtException` or `unhandledRejection` events
1323
+ await untilNextEventLoopTurn();
1324
+ }
1325
+ state.unhandledErrors.push(...state.unhandledRejectionErrorByPromise.values());
1326
+ }
1327
+ };
1328
+ };
1329
+ exports.unhandledRejectionHandler = unhandledRejectionHandler;
1330
+
1331
+ /***/ },
1332
+
1333
+ /***/ "./src/utils.ts"
1334
+ (__unused_webpack_module, exports, __webpack_require__) {
1335
+
1336
+
1337
+
1338
+ Object.defineProperty(exports, "__esModule", ({
1339
+ value: true
1340
+ }));
1341
+ exports.parseSingleTestResult = exports.makeTest = exports.makeSingleTestResult = exports.makeRunResult = exports.makeDescribe = exports.getTestID = exports.getTestDuration = exports.getEachHooksForTest = exports.getAllHooksForDescribe = exports.describeBlockHasTests = exports.createTestCaseStartInfo = exports.callAsyncCircusFn = exports.addErrorToEachTestUnderDescribe = void 0;
1342
+ var path = _interopRequireWildcard(require("path"));
1343
+ var _co = _interopRequireDefault(require("co"));
1344
+ var _dedent = _interopRequireDefault(require("dedent"));
1345
+ var _isGeneratorFn = _interopRequireDefault(require("is-generator-fn"));
1346
+ var _slash = _interopRequireDefault(require("slash"));
1347
+ var _stackUtils = _interopRequireDefault(require("stack-utils"));
1348
+ var _jestUtil = require("jest-util");
1349
+ var _prettyFormat = require("pretty-format");
1350
+ var _state = __webpack_require__("./src/state.ts");
1351
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1352
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
1353
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
1354
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
1355
+ var jestNow = globalThis[Symbol.for('jest-native-now')] || globalThis.Date.now;
1356
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
1357
+ var Promise = globalThis[Symbol.for('jest-native-promise')] || globalThis.Promise;
1358
+ /**
1359
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1360
+ *
1361
+ * This source code is licensed under the MIT license found in the
1362
+ * LICENSE file in the root directory of this source tree.
1363
+ */
1364
+ const stackUtils = new _stackUtils.default({
1365
+ cwd: 'A path that does not exist'
1366
+ });
1367
+ const jestEachBuildDir = (0, _slash.default)(path.dirname(require.resolve('jest-each')));
1368
+ function takesDoneCallback(fn) {
1369
+ return fn.length > 0;
1370
+ }
1371
+ function isGeneratorFunction(fn) {
1372
+ return (0, _isGeneratorFn.default)(fn);
1373
+ }
1374
+ const makeDescribe = (name, parent, mode) => {
1375
+ let _mode = mode;
1376
+ if (parent && !mode) {
1377
+ // If not set explicitly, inherit from the parent describe.
1378
+ _mode = parent.mode;
1379
+ }
1380
+ return {
1381
+ type: 'describeBlock',
1382
+ // eslint-disable-next-line sort-keys
1383
+ children: [],
1384
+ hooks: [],
1385
+ mode: _mode,
1386
+ name: (0, _jestUtil.convertDescriptorToString)(name),
1387
+ parent,
1388
+ tests: []
1389
+ };
1390
+ };
1391
+ exports.makeDescribe = makeDescribe;
1392
+ const makeTest = (fn, mode, concurrent, name, parent, timeout, asyncError, failing) => ({
1393
+ type: 'test',
1394
+ // eslint-disable-next-line sort-keys
1395
+ asyncError,
1396
+ concurrent,
1397
+ duration: null,
1398
+ errors: [],
1399
+ failing,
1400
+ fn,
1401
+ invocations: 0,
1402
+ mode,
1403
+ name: (0, _jestUtil.convertDescriptorToString)(name),
1404
+ numPassingAsserts: 0,
1405
+ parent,
1406
+ retryReasons: [],
1407
+ seenDone: false,
1408
+ startedAt: null,
1409
+ status: null,
1410
+ timeout,
1411
+ unhandledRejectionErrorByPromise: new Map()
1412
+ });
1413
+
1414
+ // Traverse the tree of describe blocks and return true if at least one describe
1415
+ // block has an enabled test.
1416
+ exports.makeTest = makeTest;
1417
+ const hasEnabledTest = describeBlock => {
1418
+ const {
1419
+ hasFocusedTests,
1420
+ testNamePattern
1421
+ } = (0, _state.getState)();
1422
+ return describeBlock.children.some(child => child.type === 'describeBlock' ? hasEnabledTest(child) : !(child.mode === 'skip' || hasFocusedTests && child.mode !== 'only' || testNamePattern && !testNamePattern.test(getTestID(child))));
1423
+ };
1424
+ const getAllHooksForDescribe = describe => {
1425
+ const result = {
1426
+ afterAll: [],
1427
+ beforeAll: []
1428
+ };
1429
+ if (hasEnabledTest(describe)) {
1430
+ for (const hook of describe.hooks) {
1431
+ switch (hook.type) {
1432
+ case 'beforeAll':
1433
+ result.beforeAll.push(hook);
1434
+ break;
1435
+ case 'afterAll':
1436
+ result.afterAll.push(hook);
1437
+ break;
1438
+ }
1439
+ }
1440
+ }
1441
+ return result;
1442
+ };
1443
+ exports.getAllHooksForDescribe = getAllHooksForDescribe;
1444
+ const getEachHooksForTest = test => {
1445
+ const result = {
1446
+ afterEach: [],
1447
+ beforeEach: []
1448
+ };
1449
+ if (test.concurrent) {
1450
+ // *Each hooks are not run for concurrent tests
1451
+ return result;
1452
+ }
1453
+ let block = test.parent;
1454
+ do {
1455
+ const beforeEachForCurrentBlock = [];
1456
+ for (const hook of block.hooks) {
1457
+ switch (hook.type) {
1458
+ case 'beforeEach':
1459
+ beforeEachForCurrentBlock.push(hook);
1460
+ break;
1461
+ case 'afterEach':
1462
+ result.afterEach.push(hook);
1463
+ break;
1464
+ }
1465
+ }
1466
+ // 'beforeEach' hooks are executed from top to bottom, the opposite of the
1467
+ // way we traversed it.
1468
+ result.beforeEach.unshift(...beforeEachForCurrentBlock);
1469
+ } while (block = block.parent);
1470
+ return result;
1471
+ };
1472
+ exports.getEachHooksForTest = getEachHooksForTest;
1473
+ const describeBlockHasTests = describe => describe.children.some(child => child.type === 'test' || describeBlockHasTests(child));
1474
+ exports.describeBlockHasTests = describeBlockHasTests;
1475
+ const _makeTimeoutMessage = (timeout, isHook, takesDoneCallback) => `Exceeded timeout of ${(0, _jestUtil.formatTime)(timeout)} for a ${isHook ? 'hook' : 'test'}${takesDoneCallback ? ' while waiting for `done()` to be called' : ''}.\nAdd a timeout value to this test to increase the timeout, if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout.`;
1476
+
1477
+ // Global values can be overwritten by mocks or tests. We'll capture
1478
+ // the original values in the variables before we require any files.
1479
+ const {
1480
+ setTimeout,
1481
+ clearTimeout
1482
+ } = globalThis;
1483
+ function checkIsError(error) {
1484
+ return !!(error && error.message && error.stack);
1485
+ }
1486
+ const callAsyncCircusFn = (testOrHook, testContext, {
1487
+ isHook,
1488
+ timeout
1489
+ }) => {
1490
+ let timeoutID;
1491
+ let completed = false;
1492
+ const {
1493
+ fn,
1494
+ asyncError
1495
+ } = testOrHook;
1496
+ const doneCallback = takesDoneCallback(fn);
1497
+ return new Promise((resolve, reject) => {
1498
+ timeoutID = setTimeout(() => reject(_makeTimeoutMessage(timeout, isHook, doneCallback)), timeout);
1499
+
1500
+ // If this fn accepts `done` callback we return a promise that fulfills as
1501
+ // soon as `done` called.
1502
+ if (doneCallback) {
1503
+ let returnedValue = undefined;
1504
+ const done = reason => {
1505
+ // We need to keep a stack here before the promise tick
1506
+ const errorAtDone = new _jestUtil.ErrorWithStack(undefined, done);
1507
+ if (!completed && testOrHook.seenDone) {
1508
+ errorAtDone.message = 'Expected done to be called once, but it was called multiple times.';
1509
+ if (reason) {
1510
+ errorAtDone.message += ` Reason: ${(0, _prettyFormat.format)(reason, {
1511
+ maxDepth: 3
1512
+ })}`;
1513
+ }
1514
+ reject(errorAtDone);
1515
+ throw errorAtDone;
1516
+ } else {
1517
+ testOrHook.seenDone = true;
1518
+ }
1519
+
1520
+ // Use `Promise.resolve` to allow the event loop to go a single tick in case `done` is called synchronously
1521
+ Promise.resolve().then(() => {
1522
+ if (returnedValue !== undefined) {
1523
+ asyncError.message = (0, _dedent.default)`
1524
+ Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise.
1525
+ Returned value: ${(0, _prettyFormat.format)(returnedValue, {
1526
+ maxDepth: 3
1527
+ })}
1528
+ `;
1529
+ return reject(asyncError);
1530
+ }
1531
+ let errorAsErrorObject;
1532
+ if (checkIsError(reason)) {
1533
+ errorAsErrorObject = reason;
1534
+ } else {
1535
+ errorAsErrorObject = errorAtDone;
1536
+ errorAtDone.message = `Failed: ${(0, _prettyFormat.format)(reason, {
1537
+ maxDepth: 3
1538
+ })}`;
1539
+ }
1540
+
1541
+ // Consider always throwing, regardless if `reason` is set or not
1542
+ if (completed && reason) {
1543
+ errorAsErrorObject.message = `Caught error after test environment was torn down\n\n${errorAsErrorObject.message}`;
1544
+ throw errorAsErrorObject;
1545
+ }
1546
+ return reason ? reject(errorAsErrorObject) : resolve();
1547
+ });
1548
+ };
1549
+ returnedValue = fn.call(testContext, done);
1550
+ return;
1551
+ }
1552
+ let returnedValue;
1553
+ if (isGeneratorFunction(fn)) {
1554
+ returnedValue = _co.default.wrap(fn).call({});
1555
+ } else {
1556
+ try {
1557
+ returnedValue = fn.call(testContext);
1558
+ } catch (error) {
1559
+ reject(error);
1560
+ return;
1561
+ }
1562
+ }
1563
+ if ((0, _jestUtil.isPromise)(returnedValue)) {
1564
+ returnedValue.then(() => resolve(), reject);
1565
+ return;
1566
+ }
1567
+ if (!isHook && returnedValue !== undefined) {
1568
+ reject(new Error((0, _dedent.default)`
1569
+ test functions can only return Promise or undefined.
1570
+ Returned value: ${(0, _prettyFormat.format)(returnedValue, {
1571
+ maxDepth: 3
1572
+ })}
1573
+ `));
1574
+ return;
1575
+ }
1576
+
1577
+ // Otherwise this test is synchronous, and if it didn't throw it means
1578
+ // it passed.
1579
+ resolve();
1580
+ }).finally(() => {
1581
+ completed = true;
1582
+ // If timeout is not cleared/unrefed the node process won't exit until
1583
+ // it's resolved.
1584
+ timeoutID.unref?.();
1585
+ clearTimeout(timeoutID);
1586
+ });
1587
+ };
1588
+ exports.callAsyncCircusFn = callAsyncCircusFn;
1589
+ const getTestDuration = test => {
1590
+ const {
1591
+ startedAt
1592
+ } = test;
1593
+ return typeof startedAt === 'number' ? jestNow() - startedAt : null;
1594
+ };
1595
+ exports.getTestDuration = getTestDuration;
1596
+ const makeRunResult = (describeBlock, unhandledErrors) => ({
1597
+ testResults: makeTestResults(describeBlock),
1598
+ unhandledErrors: unhandledErrors.map(_getError).map(getErrorStack)
1599
+ });
1600
+ exports.makeRunResult = makeRunResult;
1601
+ const getTestNamesPath = test => {
1602
+ const titles = [];
1603
+ let parent = test;
1604
+ do {
1605
+ titles.unshift(parent.name);
1606
+ } while (parent = parent.parent);
1607
+ return titles;
1608
+ };
1609
+ const makeSingleTestResult = test => {
1610
+ const {
1611
+ includeTestLocationInResult
1612
+ } = (0, _state.getState)();
1613
+ const {
1614
+ status
1615
+ } = test;
1616
+ (0, _jestUtil.invariant)(status, 'Status should be present after tests are run.');
1617
+ const testPath = getTestNamesPath(test);
1618
+ let location = null;
1619
+ if (includeTestLocationInResult) {
1620
+ const stackLines = test.asyncError.stack.split('\n');
1621
+ const stackLine = stackLines[1];
1622
+ let parsedLine = stackUtils.parseLine(stackLine);
1623
+ if (parsedLine?.file?.startsWith(jestEachBuildDir)) {
1624
+ const stackLine = stackLines[2];
1625
+ parsedLine = stackUtils.parseLine(stackLine);
1626
+ }
1627
+ if (parsedLine && typeof parsedLine.column === 'number' && typeof parsedLine.line === 'number') {
1628
+ location = {
1629
+ column: parsedLine.column,
1630
+ line: parsedLine.line
1631
+ };
1632
+ }
1633
+ }
1634
+ const errorsDetailed = test.errors.map(_getError);
1635
+ return {
1636
+ duration: test.duration,
1637
+ errors: errorsDetailed.map(getErrorStack),
1638
+ errorsDetailed,
1639
+ failing: test.failing,
1640
+ invocations: test.invocations,
1641
+ location,
1642
+ numPassingAsserts: test.numPassingAsserts,
1643
+ retryReasons: test.retryReasons.map(_getError).map(getErrorStack),
1644
+ startedAt: test.startedAt,
1645
+ status,
1646
+ testPath: [...testPath]
1647
+ };
1648
+ };
1649
+ exports.makeSingleTestResult = makeSingleTestResult;
1650
+ const makeTestResults = describeBlock => {
1651
+ const testResults = [];
1652
+ const stack = [[describeBlock, 0]];
1653
+ while (stack.length > 0) {
1654
+ const [currentBlock, childIndex] = stack.pop();
1655
+ for (let i = childIndex; i < currentBlock.children.length; i++) {
1656
+ const child = currentBlock.children[i];
1657
+ if (child.type === 'describeBlock') {
1658
+ stack.push([currentBlock, i + 1], [child, 0]);
1659
+ break;
1660
+ }
1661
+ if (child.type === 'test') {
1662
+ testResults.push(makeSingleTestResult(child));
1663
+ }
1664
+ }
1665
+ }
1666
+ return testResults;
1667
+ };
1668
+
1669
+ // Return a string that identifies the test (concat of parent describe block
1670
+ // names + test title)
1671
+ const getTestID = test => {
1672
+ const testNamesPath = getTestNamesPath(test);
1673
+ testNamesPath.shift(); // remove TOP_DESCRIBE_BLOCK_NAME
1674
+ return testNamesPath.join(' ');
1675
+ };
1676
+ exports.getTestID = getTestID;
1677
+ const _getError = errors => {
1678
+ let error;
1679
+ let asyncError;
1680
+ if (Array.isArray(errors)) {
1681
+ error = errors[0];
1682
+ asyncError = errors[1];
1683
+ } else {
1684
+ error = errors;
1685
+ // eslint-disable-next-line unicorn/error-message
1686
+ asyncError = new Error();
1687
+ }
1688
+ if (error && (typeof error.stack === 'string' || error.message)) {
1689
+ return error;
1690
+ }
1691
+ asyncError.message = `thrown: ${(0, _prettyFormat.format)(error, {
1692
+ maxDepth: 3
1693
+ })}`;
1694
+ return asyncError;
1695
+ };
1696
+ const getErrorStack = error => typeof error.stack === 'string' && error.stack !== '' ? error.stack : error.message;
1697
+ const addErrorToEachTestUnderDescribe = (describeBlock, error, asyncError) => {
1698
+ for (const child of describeBlock.children) {
1699
+ switch (child.type) {
1700
+ case 'describeBlock':
1701
+ addErrorToEachTestUnderDescribe(child, error, asyncError);
1702
+ break;
1703
+ case 'test':
1704
+ child.errors.push([error, asyncError]);
1705
+ break;
1706
+ }
1707
+ }
1708
+ };
1709
+ exports.addErrorToEachTestUnderDescribe = addErrorToEachTestUnderDescribe;
1710
+ const resolveTestCaseStartInfo = testNamesPath => {
1711
+ const ancestorTitles = testNamesPath.filter(name => name !== _state.ROOT_DESCRIBE_BLOCK_NAME);
1712
+ const fullName = ancestorTitles.join(' ');
1713
+ const title = testNamesPath.at(-1);
1714
+ // remove title
1715
+ ancestorTitles.pop();
1716
+ return {
1717
+ ancestorTitles,
1718
+ fullName,
1719
+ title
1720
+ };
1721
+ };
1722
+ const parseSingleTestResult = testResult => {
1723
+ let status;
1724
+ if (testResult.status === 'skip') {
1725
+ status = 'pending';
1726
+ } else if (testResult.status === 'todo') {
1727
+ status = 'todo';
1728
+ } else if (testResult.errors.length > 0) {
1729
+ status = 'failed';
1730
+ } else {
1731
+ status = 'passed';
1732
+ }
1733
+ const {
1734
+ ancestorTitles,
1735
+ fullName,
1736
+ title
1737
+ } = resolveTestCaseStartInfo(testResult.testPath);
1738
+ return {
1739
+ ancestorTitles,
1740
+ duration: testResult.duration,
1741
+ failing: testResult.failing,
1742
+ failureDetails: testResult.errorsDetailed,
1743
+ failureMessages: [...testResult.errors],
1744
+ fullName,
1745
+ invocations: testResult.invocations,
1746
+ location: testResult.location,
1747
+ numPassingAsserts: testResult.numPassingAsserts,
1748
+ retryReasons: [...testResult.retryReasons],
1749
+ startedAt: testResult.startedAt,
1750
+ status,
1751
+ title
1752
+ };
1753
+ };
1754
+ exports.parseSingleTestResult = parseSingleTestResult;
1755
+ const createTestCaseStartInfo = test => {
1756
+ const testPath = getTestNamesPath(test);
1757
+ const {
1758
+ ancestorTitles,
1759
+ fullName,
1760
+ title
1761
+ } = resolveTestCaseStartInfo(testPath);
1762
+ return {
1763
+ ancestorTitles,
1764
+ fullName,
1765
+ mode: test.mode,
1766
+ startedAt: test.startedAt,
1767
+ title
1768
+ };
1769
+ };
1770
+ exports.createTestCaseStartInfo = createTestCaseStartInfo;
1771
+
1772
+ /***/ }
1773
+
1774
+ /******/ });
1775
+ /************************************************************************/
1776
+ /******/ // The module cache
1777
+ /******/ var __webpack_module_cache__ = {};
1778
+ /******/
1779
+ /******/ // The require function
1780
+ /******/ function __webpack_require__(moduleId) {
1781
+ /******/ // Check if module is in cache
1782
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
1783
+ /******/ if (cachedModule !== undefined) {
1784
+ /******/ return cachedModule.exports;
1785
+ /******/ }
1786
+ /******/ // Create a new module (and put it into the cache)
1787
+ /******/ var module = __webpack_module_cache__[moduleId] = {
1788
+ /******/ // no module.id needed
1789
+ /******/ // no module.loaded needed
1790
+ /******/ exports: {}
1791
+ /******/ };
1792
+ /******/
1793
+ /******/ // Execute the module function
1794
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
1795
+ /******/
1796
+ /******/ // Return the exports of the module
1797
+ /******/ return module.exports;
1798
+ /******/ }
1799
+ /******/
1800
+ /************************************************************************/
1801
+ var __webpack_exports__ = {};
1802
+ // This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
1803
+ (() => {
1804
+ var exports = __webpack_exports__;
1805
+
1806
+
1807
+ Object.defineProperty(exports, "__esModule", ({
1808
+ value: true
1809
+ }));
1810
+ exports.runAndTransformResultsToJestFormat = exports.initialize = exports.eventHandler = void 0;
1811
+ var _expect = require("@jest/expect");
1812
+ var _testResult = require("@jest/test-result");
1813
+ var _jestMessageUtil = require("jest-message-util");
1814
+ var _jestSnapshot = require("jest-snapshot");
1815
+ var _ = _interopRequireDefault(__webpack_require__("./src/index.ts"));
1816
+ var _run = _interopRequireDefault(__webpack_require__("./src/run.ts"));
1817
+ var _state = __webpack_require__("./src/state.ts");
1818
+ var _testCaseReportHandler = _interopRequireDefault(__webpack_require__("./src/testCaseReportHandler.ts"));
1819
+ var _unhandledRejectionHandler = __webpack_require__("./src/unhandledRejectionHandler.ts");
1820
+ var _utils = __webpack_require__("./src/utils.ts");
1821
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1822
+ /**
1823
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1824
+ *
1825
+ * This source code is licensed under the MIT license found in the
1826
+ * LICENSE file in the root directory of this source tree.
1827
+ */
1828
+
1829
+ const initialize = async ({
1830
+ config,
1831
+ environment,
1832
+ runtime,
1833
+ globalConfig,
1834
+ localRequire,
1835
+ parentProcess,
1836
+ sendMessageToJest,
1837
+ setGlobalsForRuntime,
1838
+ testPath
1839
+ }) => {
1840
+ if (globalConfig.testTimeout) {
1841
+ (0, _state.getState)().testTimeout = globalConfig.testTimeout;
1842
+ }
1843
+ (0, _state.getState)().maxConcurrency = globalConfig.maxConcurrency;
1844
+ (0, _state.getState)().randomize = globalConfig.randomize;
1845
+ (0, _state.getState)().seed = globalConfig.seed;
1846
+
1847
+ // @ts-expect-error: missing `concurrent` which is added later
1848
+ const globalsObject = {
1849
+ ..._.default,
1850
+ fdescribe: _.default.describe.only,
1851
+ fit: _.default.it.only,
1852
+ xdescribe: _.default.describe.skip,
1853
+ xit: _.default.it.skip,
1854
+ xtest: _.default.it.skip
1855
+ };
1856
+ (0, _state.addEventHandler)(eventHandler);
1857
+ if (environment.handleTestEvent) {
1858
+ (0, _state.addEventHandler)(environment.handleTestEvent.bind(environment));
1859
+ }
1860
+ _expect.jestExpect.setState({
1861
+ expand: globalConfig.expand
1862
+ });
1863
+ const runtimeGlobals = {
1864
+ ...globalsObject,
1865
+ expect: _expect.jestExpect
1866
+ };
1867
+ setGlobalsForRuntime(runtimeGlobals);
1868
+ if (config.injectGlobals) {
1869
+ Object.assign(environment.global, runtimeGlobals);
1870
+ }
1871
+ await (0, _state.dispatch)({
1872
+ name: 'setup',
1873
+ parentProcess,
1874
+ runtimeGlobals,
1875
+ testNamePattern: globalConfig.testNamePattern
1876
+ });
1877
+ if (config.testLocationInResults) {
1878
+ await (0, _state.dispatch)({
1879
+ name: 'include_test_location_in_result'
1880
+ });
1881
+ }
1882
+
1883
+ // Jest tests snapshotSerializers in order preceding built-in serializers.
1884
+ // Therefore, add in reverse because the last added is the first tested.
1885
+ for (const path of [...config.snapshotSerializers].reverse()) (0, _jestSnapshot.addSerializer)(localRequire(path));
1886
+ const snapshotResolver = await (0, _jestSnapshot.buildSnapshotResolver)(config, localRequire);
1887
+ const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath);
1888
+ const snapshotState = new _jestSnapshot.SnapshotState(snapshotPath, {
1889
+ expand: globalConfig.expand,
1890
+ prettierPath: config.prettierPath,
1891
+ rootDir: config.rootDir,
1892
+ snapshotFormat: config.snapshotFormat,
1893
+ updateSnapshot: globalConfig.updateSnapshot
1894
+ });
1895
+ _expect.jestExpect.setState({
1896
+ snapshotState,
1897
+ testPath
1898
+ });
1899
+ (0, _state.addEventHandler)(handleSnapshotStateAfterRetry(snapshotState));
1900
+ if (sendMessageToJest) {
1901
+ (0, _state.addEventHandler)((0, _testCaseReportHandler.default)(testPath, sendMessageToJest));
1902
+ }
1903
+ (0, _state.addEventHandler)((0, _unhandledRejectionHandler.unhandledRejectionHandler)(runtime, globalConfig.waitForUnhandledRejections));
1904
+
1905
+ // Return it back to the outer scope (test runner outside the VM).
1906
+ return {
1907
+ globals: globalsObject,
1908
+ snapshotState
1909
+ };
1910
+ };
1911
+ exports.initialize = initialize;
1912
+ const runAndTransformResultsToJestFormat = async ({
1913
+ config,
1914
+ globalConfig,
1915
+ setupAfterEnvPerfStats,
1916
+ testPath
1917
+ }) => {
1918
+ const runResult = await (0, _run.default)();
1919
+ let numFailingTests = 0;
1920
+ let numPassingTests = 0;
1921
+ let numPendingTests = 0;
1922
+ let numTodoTests = 0;
1923
+ const assertionResults = runResult.testResults.map(testResult => {
1924
+ let status;
1925
+ if (testResult.status === 'skip') {
1926
+ status = 'pending';
1927
+ numPendingTests += 1;
1928
+ } else if (testResult.status === 'todo') {
1929
+ status = 'todo';
1930
+ numTodoTests += 1;
1931
+ } else if (testResult.errors.length > 0) {
1932
+ status = 'failed';
1933
+ numFailingTests += 1;
1934
+ } else {
1935
+ status = 'passed';
1936
+ numPassingTests += 1;
1937
+ }
1938
+ const ancestorTitles = testResult.testPath.filter(name => name !== _state.ROOT_DESCRIBE_BLOCK_NAME);
1939
+ const title = ancestorTitles.pop();
1940
+ return {
1941
+ ancestorTitles,
1942
+ duration: testResult.duration,
1943
+ failing: testResult.failing,
1944
+ failureDetails: testResult.errorsDetailed,
1945
+ failureMessages: testResult.errors,
1946
+ fullName: title ? [...ancestorTitles, title].join(' ') : ancestorTitles.join(' '),
1947
+ invocations: testResult.invocations,
1948
+ location: testResult.location,
1949
+ numPassingAsserts: testResult.numPassingAsserts,
1950
+ retryReasons: testResult.retryReasons,
1951
+ startAt: testResult.startedAt,
1952
+ status,
1953
+ title: testResult.testPath.at(-1)
1954
+ };
1955
+ });
1956
+ let failureMessage = (0, _jestMessageUtil.formatResultsErrors)(assertionResults, config, globalConfig, testPath);
1957
+ let testExecError;
1958
+ if (runResult.unhandledErrors.length > 0) {
1959
+ testExecError = {
1960
+ message: '',
1961
+ stack: runResult.unhandledErrors.join('\n')
1962
+ };
1963
+ failureMessage = `${failureMessage || ''}\n\n${runResult.unhandledErrors.map(err => (0, _jestMessageUtil.formatExecError)(err, config, globalConfig)).join('\n')}`;
1964
+ }
1965
+ await (0, _state.dispatch)({
1966
+ name: 'teardown'
1967
+ });
1968
+ const emptyTestResult = (0, _testResult.createEmptyTestResult)();
1969
+ return {
1970
+ ...emptyTestResult,
1971
+ console: undefined,
1972
+ displayName: config.displayName,
1973
+ failureMessage,
1974
+ numFailingTests,
1975
+ numPassingTests,
1976
+ numPendingTests,
1977
+ numTodoTests,
1978
+ perfStats: {
1979
+ ...emptyTestResult.perfStats,
1980
+ ...setupAfterEnvPerfStats
1981
+ },
1982
+ testExecError,
1983
+ testFilePath: testPath,
1984
+ testResults: assertionResults
1985
+ };
1986
+ };
1987
+ exports.runAndTransformResultsToJestFormat = runAndTransformResultsToJestFormat;
1988
+ const handleSnapshotStateAfterRetry = snapshotState => event => {
1989
+ switch (event.name) {
1990
+ case 'test_retry':
1991
+ {
1992
+ // Clear any snapshot data that occurred in previous test run
1993
+ snapshotState.clear();
1994
+ }
1995
+ }
1996
+ };
1997
+
1998
+ // Exported for direct access from unit tests.
1999
+ const eventHandler = async event => {
2000
+ switch (event.name) {
2001
+ case 'test_start':
2002
+ {
2003
+ _expect.jestExpect.setState({
2004
+ currentTestName: (0, _utils.getTestID)(event.test),
2005
+ testFailing: event.test.failing
2006
+ });
2007
+ break;
2008
+ }
2009
+ case 'test_done':
2010
+ {
2011
+ event.test.numPassingAsserts = _expect.jestExpect.getState().numPassingAsserts;
2012
+ _addSuppressedErrors(event.test);
2013
+ _addExpectedAssertionErrors(event.test);
2014
+ break;
2015
+ }
2016
+ }
2017
+ };
2018
+ exports.eventHandler = eventHandler;
2019
+ const _addExpectedAssertionErrors = test => {
2020
+ const {
2021
+ isExpectingAssertions
2022
+ } = _expect.jestExpect.getState();
2023
+ const failures = _expect.jestExpect.extractExpectedAssertionsErrors();
2024
+ if (isExpectingAssertions && test.errors.length > 0) {
2025
+ // Only show errors from `expect.hasAssertions()` when no other failure has happened.
2026
+ return;
2027
+ }
2028
+ test.errors.push(...failures.map(failure => failure.error));
2029
+ };
2030
+
2031
+ // Get suppressed errors from ``jest-matchers`` that weren't throw during
2032
+ // test execution and add them to the test result, potentially failing
2033
+ // a passing test.
2034
+ const _addSuppressedErrors = test => {
2035
+ const {
2036
+ suppressedErrors
2037
+ } = _expect.jestExpect.getState();
2038
+ _expect.jestExpect.setState({
2039
+ suppressedErrors: []
2040
+ });
2041
+ if (suppressedErrors.length > 0) {
2042
+ test.errors.push(...suppressedErrors);
2043
+ }
2044
+ };
2045
+ })();
2046
+
2047
+ module.exports = __webpack_exports__;
2048
+ /******/ })()
2049
+ ;