@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.
package/build/index.js ADDED
@@ -0,0 +1,1670 @@
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/run.ts"
513
+ (__unused_webpack_module, exports, __webpack_require__) {
514
+
515
+
516
+
517
+ Object.defineProperty(exports, "__esModule", ({
518
+ value: true
519
+ }));
520
+ exports["default"] = void 0;
521
+ var _async_hooks = require("async_hooks");
522
+ var _pLimit = _interopRequireDefault(require("p-limit"));
523
+ var _expect = require("@jest/expect");
524
+ var _jestUtil = require("jest-util");
525
+ var _shuffleArray = _interopRequireWildcard(__webpack_require__("./src/shuffleArray.ts"));
526
+ var _state = __webpack_require__("./src/state.ts");
527
+ var _types = __webpack_require__("./src/types.ts");
528
+ var _utils = __webpack_require__("./src/utils.ts");
529
+ 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); }
530
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
531
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
532
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
533
+ var Promise = globalThis[Symbol.for('jest-native-promise')] || globalThis.Promise;
534
+ /**
535
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
536
+ *
537
+ * This source code is licensed under the MIT license found in the
538
+ * LICENSE file in the root directory of this source tree.
539
+ */
540
+ // Global values can be overwritten by mocks or tests. We'll capture
541
+ // the original values in the variables before we require any files.
542
+ const {
543
+ setTimeout
544
+ } = globalThis;
545
+ const testNameStorage = new _async_hooks.AsyncLocalStorage();
546
+ const run = async () => {
547
+ const {
548
+ rootDescribeBlock,
549
+ seed,
550
+ randomize
551
+ } = (0, _state.getState)();
552
+ _expect.jestExpect.setState({
553
+ currentConcurrentTestName: () => testNameStorage.getStore()
554
+ });
555
+ const rng = randomize ? (0, _shuffleArray.rngBuilder)(seed) : undefined;
556
+ await (0, _state.dispatch)({
557
+ name: 'run_start'
558
+ });
559
+ await _runTestsForDescribeBlock(rootDescribeBlock, rng);
560
+ await (0, _state.dispatch)({
561
+ name: 'run_finish'
562
+ });
563
+ return (0, _utils.makeRunResult)((0, _state.getState)().rootDescribeBlock, (0, _state.getState)().unhandledErrors);
564
+ };
565
+ function* regroupConcurrentChildren(children) {
566
+ const concurrentTests = children.filter(child => child.type === 'test' && child.concurrent);
567
+ if (concurrentTests.length === 0) {
568
+ yield* children;
569
+ return;
570
+ }
571
+ let collectedConcurrent = false;
572
+ for (const child of children) {
573
+ if (child.type === 'test' && child.concurrent) {
574
+ if (!collectedConcurrent) {
575
+ collectedConcurrent = true;
576
+ yield {
577
+ tests: concurrentTests,
578
+ type: 'test-concurrent'
579
+ };
580
+ }
581
+ } else {
582
+ yield child;
583
+ }
584
+ }
585
+ }
586
+ const _runTestsForDescribeBlock = async (describeBlock, rng) => {
587
+ await (0, _state.dispatch)({
588
+ describeBlock,
589
+ name: 'run_describe_start'
590
+ });
591
+ const {
592
+ beforeAll,
593
+ afterAll
594
+ } = (0, _utils.getAllHooksForDescribe)(describeBlock);
595
+ const isSkipped = describeBlock.mode === 'skip';
596
+ if (!isSkipped) {
597
+ for (const hook of beforeAll) {
598
+ await _callCircusHook({
599
+ describeBlock,
600
+ hook
601
+ });
602
+ }
603
+ }
604
+
605
+ // Tests that fail and are retried we run after other tests
606
+ const retryTimes = Number.parseInt(globalThis[_types.RETRY_TIMES], 10) || 0;
607
+ const hasRetryTimes = retryTimes > 0;
608
+ const waitBeforeRetry = Number.parseInt(globalThis[_types.WAIT_BEFORE_RETRY], 10) || 0;
609
+ const retryImmediately = globalThis[_types.RETRY_IMMEDIATELY] || false;
610
+ const deferredRetryTests = [];
611
+ if (rng) {
612
+ describeBlock.children = (0, _shuffleArray.default)(describeBlock.children, rng);
613
+ }
614
+ // Regroup concurrent tests as a single "sequential" unit
615
+ const children = regroupConcurrentChildren(describeBlock.children);
616
+ const rerunTest = async test => {
617
+ let numRetriesAvailable = retryTimes;
618
+ while (numRetriesAvailable > 0 && test.errors.length > 0) {
619
+ // Clear errors so retries occur
620
+ await (0, _state.dispatch)({
621
+ name: 'test_retry',
622
+ test
623
+ });
624
+ if (waitBeforeRetry > 0) {
625
+ await new Promise(resolve => setTimeout(resolve, waitBeforeRetry));
626
+ }
627
+ await _runTest(test, isSkipped);
628
+ numRetriesAvailable--;
629
+ }
630
+ };
631
+ const handleRetry = async (test, hasErrorsBeforeTestRun, hasRetryTimes) => {
632
+ // no retry if the test passed or had errors before the test ran
633
+ if (test.errors.length === 0 || hasErrorsBeforeTestRun || !hasRetryTimes) {
634
+ return;
635
+ }
636
+ if (!retryImmediately) {
637
+ deferredRetryTests.push(test);
638
+ return;
639
+ }
640
+
641
+ // If immediate retry is set, we retry the test immediately after the first run
642
+ await rerunTest(test);
643
+ };
644
+ const runTestWithContext = async child => {
645
+ const hasErrorsBeforeTestRun = child.errors.length > 0;
646
+ return testNameStorage.run((0, _utils.getTestID)(child), async () => {
647
+ await _runTest(child, isSkipped);
648
+ await handleRetry(child, hasErrorsBeforeTestRun, hasRetryTimes);
649
+ });
650
+ };
651
+ for (const child of children) {
652
+ switch (child.type) {
653
+ case 'describeBlock':
654
+ {
655
+ await _runTestsForDescribeBlock(child, rng);
656
+ break;
657
+ }
658
+ case 'test':
659
+ {
660
+ await runTestWithContext(child);
661
+ break;
662
+ }
663
+ case 'test-concurrent':
664
+ {
665
+ await (0, _state.dispatch)({
666
+ describeBlock,
667
+ name: 'concurrent_tests_start',
668
+ tests: child.tests
669
+ });
670
+ const concurrencyLimiter = (0, _pLimit.default)((0, _state.getState)().maxConcurrency);
671
+ const tasks = child.tests.map(concurrentTest => concurrencyLimiter(() => runTestWithContext(concurrentTest)));
672
+ await Promise.all(tasks);
673
+ await (0, _state.dispatch)({
674
+ describeBlock,
675
+ name: 'concurrent_tests_end',
676
+ tests: child.tests
677
+ });
678
+ break;
679
+ }
680
+ }
681
+ }
682
+
683
+ // Re-run failed tests n-times if configured
684
+ for (const test of deferredRetryTests) {
685
+ await rerunTest(test);
686
+ }
687
+ if (!isSkipped) {
688
+ for (const hook of afterAll) {
689
+ await _callCircusHook({
690
+ describeBlock,
691
+ hook
692
+ });
693
+ }
694
+ }
695
+ await (0, _state.dispatch)({
696
+ describeBlock,
697
+ name: 'run_describe_finish'
698
+ });
699
+ };
700
+ const _runTest = async (test, parentSkipped) => {
701
+ await (0, _state.dispatch)({
702
+ name: 'test_start',
703
+ test
704
+ });
705
+ const testContext = Object.create(null);
706
+ const {
707
+ hasFocusedTests,
708
+ testNamePattern
709
+ } = (0, _state.getState)();
710
+ const isSkipped = parentSkipped || test.mode === 'skip' || hasFocusedTests && test.mode === undefined || testNamePattern && !testNamePattern.test((0, _utils.getTestID)(test));
711
+ if (isSkipped) {
712
+ await (0, _state.dispatch)({
713
+ name: 'test_skip',
714
+ test
715
+ });
716
+ return;
717
+ }
718
+ if (test.mode === 'todo') {
719
+ await (0, _state.dispatch)({
720
+ name: 'test_todo',
721
+ test
722
+ });
723
+ return;
724
+ }
725
+ await (0, _state.dispatch)({
726
+ name: 'test_started',
727
+ test
728
+ });
729
+ const {
730
+ afterEach,
731
+ beforeEach
732
+ } = (0, _utils.getEachHooksForTest)(test);
733
+ for (const hook of beforeEach) {
734
+ if (test.errors.length > 0) {
735
+ // If any of the before hooks failed already, we don't run any
736
+ // hooks after that.
737
+ break;
738
+ }
739
+ await _callCircusHook({
740
+ hook,
741
+ test,
742
+ testContext
743
+ });
744
+ }
745
+ await _callCircusTest(test, testContext);
746
+ for (const hook of afterEach) {
747
+ await _callCircusHook({
748
+ hook,
749
+ test,
750
+ testContext
751
+ });
752
+ }
753
+
754
+ // `afterAll` hooks should not affect test status (pass or fail), because if
755
+ // we had a global `afterAll` hook it would block all existing tests until
756
+ // this hook is executed. So we dispatch `test_done` right away.
757
+ await (0, _state.dispatch)({
758
+ name: 'test_done',
759
+ test
760
+ });
761
+ };
762
+ const _callCircusHook = async ({
763
+ hook,
764
+ test,
765
+ describeBlock,
766
+ testContext = {}
767
+ }) => {
768
+ await (0, _state.dispatch)({
769
+ hook,
770
+ name: 'hook_start'
771
+ });
772
+ const timeout = hook.timeout || (0, _state.getState)().testTimeout;
773
+ try {
774
+ await (0, _utils.callAsyncCircusFn)(hook, testContext, {
775
+ isHook: true,
776
+ timeout
777
+ });
778
+ await (0, _state.dispatch)({
779
+ describeBlock,
780
+ hook,
781
+ name: 'hook_success',
782
+ test
783
+ });
784
+ } catch (error) {
785
+ await (0, _state.dispatch)({
786
+ describeBlock,
787
+ error,
788
+ hook,
789
+ name: 'hook_failure',
790
+ test
791
+ });
792
+ }
793
+ };
794
+ const _callCircusTest = async (test, testContext) => {
795
+ await (0, _state.dispatch)({
796
+ name: 'test_fn_start',
797
+ test
798
+ });
799
+ const timeout = test.timeout || (0, _state.getState)().testTimeout;
800
+ (0, _jestUtil.invariant)(test.fn, "Tests with no 'fn' should have 'mode' set to 'skipped'");
801
+ if (test.errors.length > 0) {
802
+ return; // We don't run the test if there's already an error in before hooks.
803
+ }
804
+ try {
805
+ await (0, _utils.callAsyncCircusFn)(test, testContext, {
806
+ isHook: false,
807
+ timeout
808
+ });
809
+ if (test.failing) {
810
+ test.asyncError.message = 'Failing test passed even though it was supposed to fail. Remove `.failing` to remove error.';
811
+ await (0, _state.dispatch)({
812
+ error: test.asyncError,
813
+ name: 'test_fn_failure',
814
+ test
815
+ });
816
+ } else {
817
+ await (0, _state.dispatch)({
818
+ name: 'test_fn_success',
819
+ test
820
+ });
821
+ }
822
+ } catch (error) {
823
+ if (test.failing) {
824
+ await (0, _state.dispatch)({
825
+ name: 'test_fn_success',
826
+ test
827
+ });
828
+ } else {
829
+ await (0, _state.dispatch)({
830
+ error,
831
+ name: 'test_fn_failure',
832
+ test
833
+ });
834
+ }
835
+ }
836
+ };
837
+ var _default = exports["default"] = run;
838
+
839
+ /***/ },
840
+
841
+ /***/ "./src/shuffleArray.ts"
842
+ (__unused_webpack_module, exports) {
843
+
844
+
845
+
846
+ Object.defineProperty(exports, "__esModule", ({
847
+ value: true
848
+ }));
849
+ exports["default"] = shuffleArray;
850
+ exports.rngBuilder = void 0;
851
+ var _pureRand = require("pure-rand");
852
+ /**
853
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
854
+ *
855
+ * This source code is licensed under the MIT license found in the
856
+ * LICENSE file in the root directory of this source tree.
857
+ */
858
+
859
+ // Generates [from, to] inclusive
860
+
861
+ const rngBuilder = seed => {
862
+ const gen = (0, _pureRand.xoroshiro128plus)(seed);
863
+ return {
864
+ next: (from, to) => (0, _pureRand.unsafeUniformIntDistribution)(from, to, gen)
865
+ };
866
+ };
867
+
868
+ // Fisher-Yates shuffle
869
+ // This is performed in-place
870
+ exports.rngBuilder = rngBuilder;
871
+ function shuffleArray(array, random) {
872
+ const length = array.length;
873
+ if (length === 0) {
874
+ return [];
875
+ }
876
+ for (let i = 0; i < length; i++) {
877
+ const n = random.next(i, length - 1);
878
+ const value = array[i];
879
+ array[i] = array[n];
880
+ array[n] = value;
881
+ }
882
+ return array;
883
+ }
884
+
885
+ /***/ },
886
+
887
+ /***/ "./src/state.ts"
888
+ (__unused_webpack_module, exports, __webpack_require__) {
889
+
890
+
891
+
892
+ Object.defineProperty(exports, "__esModule", ({
893
+ value: true
894
+ }));
895
+ exports.setState = exports.resetState = exports.removeEventHandler = exports.getState = exports.dispatchSync = exports.dispatch = exports.addEventHandler = exports.ROOT_DESCRIBE_BLOCK_NAME = void 0;
896
+ var _jestUtil = require("jest-util");
897
+ var _eventHandler = _interopRequireDefault(__webpack_require__("./src/eventHandler.ts"));
898
+ var _formatNodeAssertErrors = _interopRequireDefault(__webpack_require__("./src/formatNodeAssertErrors.ts"));
899
+ var _types = __webpack_require__("./src/types.ts");
900
+ var _utils = __webpack_require__("./src/utils.ts");
901
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
902
+ /**
903
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
904
+ *
905
+ * This source code is licensed under the MIT license found in the
906
+ * LICENSE file in the root directory of this source tree.
907
+ */
908
+
909
+ const handlers = globalThis[_types.EVENT_HANDLERS] || [_eventHandler.default, _formatNodeAssertErrors.default];
910
+ (0, _jestUtil.setGlobal)(globalThis, _types.EVENT_HANDLERS, handlers, 'retain');
911
+ const ROOT_DESCRIBE_BLOCK_NAME = exports.ROOT_DESCRIBE_BLOCK_NAME = 'ROOT_DESCRIBE_BLOCK';
912
+ const createState = () => {
913
+ const ROOT_DESCRIBE_BLOCK = (0, _utils.makeDescribe)(ROOT_DESCRIBE_BLOCK_NAME);
914
+ return {
915
+ currentDescribeBlock: ROOT_DESCRIBE_BLOCK,
916
+ currentlyRunningTest: null,
917
+ expand: undefined,
918
+ hasFocusedTests: false,
919
+ hasStarted: false,
920
+ includeTestLocationInResult: false,
921
+ maxConcurrency: 5,
922
+ parentProcess: null,
923
+ rootDescribeBlock: ROOT_DESCRIBE_BLOCK,
924
+ seed: 0,
925
+ testNamePattern: null,
926
+ testTimeout: 5000,
927
+ unhandledErrors: [],
928
+ unhandledRejectionErrorByPromise: new Map()
929
+ };
930
+ };
931
+ const getState = () => globalThis[_types.STATE_SYM];
932
+ exports.getState = getState;
933
+ const setState = state => {
934
+ (0, _jestUtil.setGlobal)(globalThis, _types.STATE_SYM, state);
935
+ (0, _jestUtil.protectProperties)(state, ['hasFocusedTests', 'hasStarted', 'includeTestLocationInResult', 'maxConcurrency', 'seed', 'testNamePattern', 'testTimeout', 'unhandledErrors', 'unhandledRejectionErrorByPromise']);
936
+ return state;
937
+ };
938
+ exports.setState = setState;
939
+ const resetState = () => {
940
+ setState(createState());
941
+ };
942
+ exports.resetState = resetState;
943
+ resetState();
944
+ const dispatch = async event => {
945
+ for (const handler of handlers) {
946
+ await handler(event, getState());
947
+ }
948
+ };
949
+ exports.dispatch = dispatch;
950
+ const dispatchSync = event => {
951
+ for (const handler of handlers) {
952
+ handler(event, getState());
953
+ }
954
+ };
955
+ exports.dispatchSync = dispatchSync;
956
+ const addEventHandler = handler => {
957
+ handlers.push(handler);
958
+ };
959
+ exports.addEventHandler = addEventHandler;
960
+ const removeEventHandler = handler => {
961
+ const index = handlers.lastIndexOf(handler);
962
+ if (index !== -1) {
963
+ handlers.splice(index, 1);
964
+ }
965
+ };
966
+ exports.removeEventHandler = removeEventHandler;
967
+
968
+ /***/ },
969
+
970
+ /***/ "./src/types.ts"
971
+ (__unused_webpack_module, exports) {
972
+
973
+
974
+
975
+ Object.defineProperty(exports, "__esModule", ({
976
+ value: true
977
+ }));
978
+ 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;
979
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
980
+ /**
981
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
982
+ *
983
+ * This source code is licensed under the MIT license found in the
984
+ * LICENSE file in the root directory of this source tree.
985
+ */
986
+
987
+ const STATE_SYM = exports.STATE_SYM = Symbol('JEST_STATE_SYMBOL');
988
+ const RETRY_TIMES = exports.RETRY_TIMES = Symbol.for('RETRY_TIMES');
989
+ const RETRY_IMMEDIATELY = exports.RETRY_IMMEDIATELY = Symbol.for('RETRY_IMMEDIATELY');
990
+ const WAIT_BEFORE_RETRY = exports.WAIT_BEFORE_RETRY = Symbol.for('WAIT_BEFORE_RETRY');
991
+ // To pass this value from Runtime object to state we need to use global[sym]
992
+ const TEST_TIMEOUT_SYMBOL = exports.TEST_TIMEOUT_SYMBOL = Symbol.for('TEST_TIMEOUT_SYMBOL');
993
+ const EVENT_HANDLERS = exports.EVENT_HANDLERS = Symbol.for('EVENT_HANDLERS');
994
+ const LOG_ERRORS_BEFORE_RETRY = exports.LOG_ERRORS_BEFORE_RETRY = Symbol.for('LOG_ERRORS_BEFORE_RETRY');
995
+
996
+ /***/ },
997
+
998
+ /***/ "./src/utils.ts"
999
+ (__unused_webpack_module, exports, __webpack_require__) {
1000
+
1001
+
1002
+
1003
+ Object.defineProperty(exports, "__esModule", ({
1004
+ value: true
1005
+ }));
1006
+ 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;
1007
+ var path = _interopRequireWildcard(require("path"));
1008
+ var _co = _interopRequireDefault(require("co"));
1009
+ var _dedent = _interopRequireDefault(require("dedent"));
1010
+ var _isGeneratorFn = _interopRequireDefault(require("is-generator-fn"));
1011
+ var _slash = _interopRequireDefault(require("slash"));
1012
+ var _stackUtils = _interopRequireDefault(require("stack-utils"));
1013
+ var _jestUtil = require("jest-util");
1014
+ var _prettyFormat = require("pretty-format");
1015
+ var _state = __webpack_require__("./src/state.ts");
1016
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1017
+ 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); }
1018
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
1019
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
1020
+ var jestNow = globalThis[Symbol.for('jest-native-now')] || globalThis.Date.now;
1021
+ var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
1022
+ var Promise = globalThis[Symbol.for('jest-native-promise')] || globalThis.Promise;
1023
+ /**
1024
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1025
+ *
1026
+ * This source code is licensed under the MIT license found in the
1027
+ * LICENSE file in the root directory of this source tree.
1028
+ */
1029
+ const stackUtils = new _stackUtils.default({
1030
+ cwd: 'A path that does not exist'
1031
+ });
1032
+ const jestEachBuildDir = (0, _slash.default)(path.dirname(require.resolve('jest-each')));
1033
+ function takesDoneCallback(fn) {
1034
+ return fn.length > 0;
1035
+ }
1036
+ function isGeneratorFunction(fn) {
1037
+ return (0, _isGeneratorFn.default)(fn);
1038
+ }
1039
+ const makeDescribe = (name, parent, mode) => {
1040
+ let _mode = mode;
1041
+ if (parent && !mode) {
1042
+ // If not set explicitly, inherit from the parent describe.
1043
+ _mode = parent.mode;
1044
+ }
1045
+ return {
1046
+ type: 'describeBlock',
1047
+ // eslint-disable-next-line sort-keys
1048
+ children: [],
1049
+ hooks: [],
1050
+ mode: _mode,
1051
+ name: (0, _jestUtil.convertDescriptorToString)(name),
1052
+ parent,
1053
+ tests: []
1054
+ };
1055
+ };
1056
+ exports.makeDescribe = makeDescribe;
1057
+ const makeTest = (fn, mode, concurrent, name, parent, timeout, asyncError, failing) => ({
1058
+ type: 'test',
1059
+ // eslint-disable-next-line sort-keys
1060
+ asyncError,
1061
+ concurrent,
1062
+ duration: null,
1063
+ errors: [],
1064
+ failing,
1065
+ fn,
1066
+ invocations: 0,
1067
+ mode,
1068
+ name: (0, _jestUtil.convertDescriptorToString)(name),
1069
+ numPassingAsserts: 0,
1070
+ parent,
1071
+ retryReasons: [],
1072
+ seenDone: false,
1073
+ startedAt: null,
1074
+ status: null,
1075
+ timeout,
1076
+ unhandledRejectionErrorByPromise: new Map()
1077
+ });
1078
+
1079
+ // Traverse the tree of describe blocks and return true if at least one describe
1080
+ // block has an enabled test.
1081
+ exports.makeTest = makeTest;
1082
+ const hasEnabledTest = describeBlock => {
1083
+ const {
1084
+ hasFocusedTests,
1085
+ testNamePattern
1086
+ } = (0, _state.getState)();
1087
+ return describeBlock.children.some(child => child.type === 'describeBlock' ? hasEnabledTest(child) : !(child.mode === 'skip' || hasFocusedTests && child.mode !== 'only' || testNamePattern && !testNamePattern.test(getTestID(child))));
1088
+ };
1089
+ const getAllHooksForDescribe = describe => {
1090
+ const result = {
1091
+ afterAll: [],
1092
+ beforeAll: []
1093
+ };
1094
+ if (hasEnabledTest(describe)) {
1095
+ for (const hook of describe.hooks) {
1096
+ switch (hook.type) {
1097
+ case 'beforeAll':
1098
+ result.beforeAll.push(hook);
1099
+ break;
1100
+ case 'afterAll':
1101
+ result.afterAll.push(hook);
1102
+ break;
1103
+ }
1104
+ }
1105
+ }
1106
+ return result;
1107
+ };
1108
+ exports.getAllHooksForDescribe = getAllHooksForDescribe;
1109
+ const getEachHooksForTest = test => {
1110
+ const result = {
1111
+ afterEach: [],
1112
+ beforeEach: []
1113
+ };
1114
+ if (test.concurrent) {
1115
+ // *Each hooks are not run for concurrent tests
1116
+ return result;
1117
+ }
1118
+ let block = test.parent;
1119
+ do {
1120
+ const beforeEachForCurrentBlock = [];
1121
+ for (const hook of block.hooks) {
1122
+ switch (hook.type) {
1123
+ case 'beforeEach':
1124
+ beforeEachForCurrentBlock.push(hook);
1125
+ break;
1126
+ case 'afterEach':
1127
+ result.afterEach.push(hook);
1128
+ break;
1129
+ }
1130
+ }
1131
+ // 'beforeEach' hooks are executed from top to bottom, the opposite of the
1132
+ // way we traversed it.
1133
+ result.beforeEach.unshift(...beforeEachForCurrentBlock);
1134
+ } while (block = block.parent);
1135
+ return result;
1136
+ };
1137
+ exports.getEachHooksForTest = getEachHooksForTest;
1138
+ const describeBlockHasTests = describe => describe.children.some(child => child.type === 'test' || describeBlockHasTests(child));
1139
+ exports.describeBlockHasTests = describeBlockHasTests;
1140
+ 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.`;
1141
+
1142
+ // Global values can be overwritten by mocks or tests. We'll capture
1143
+ // the original values in the variables before we require any files.
1144
+ const {
1145
+ setTimeout,
1146
+ clearTimeout
1147
+ } = globalThis;
1148
+ function checkIsError(error) {
1149
+ return !!(error && error.message && error.stack);
1150
+ }
1151
+ const callAsyncCircusFn = (testOrHook, testContext, {
1152
+ isHook,
1153
+ timeout
1154
+ }) => {
1155
+ let timeoutID;
1156
+ let completed = false;
1157
+ const {
1158
+ fn,
1159
+ asyncError
1160
+ } = testOrHook;
1161
+ const doneCallback = takesDoneCallback(fn);
1162
+ return new Promise((resolve, reject) => {
1163
+ timeoutID = setTimeout(() => reject(_makeTimeoutMessage(timeout, isHook, doneCallback)), timeout);
1164
+
1165
+ // If this fn accepts `done` callback we return a promise that fulfills as
1166
+ // soon as `done` called.
1167
+ if (doneCallback) {
1168
+ let returnedValue = undefined;
1169
+ const done = reason => {
1170
+ // We need to keep a stack here before the promise tick
1171
+ const errorAtDone = new _jestUtil.ErrorWithStack(undefined, done);
1172
+ if (!completed && testOrHook.seenDone) {
1173
+ errorAtDone.message = 'Expected done to be called once, but it was called multiple times.';
1174
+ if (reason) {
1175
+ errorAtDone.message += ` Reason: ${(0, _prettyFormat.format)(reason, {
1176
+ maxDepth: 3
1177
+ })}`;
1178
+ }
1179
+ reject(errorAtDone);
1180
+ throw errorAtDone;
1181
+ } else {
1182
+ testOrHook.seenDone = true;
1183
+ }
1184
+
1185
+ // Use `Promise.resolve` to allow the event loop to go a single tick in case `done` is called synchronously
1186
+ Promise.resolve().then(() => {
1187
+ if (returnedValue !== undefined) {
1188
+ asyncError.message = (0, _dedent.default)`
1189
+ Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise.
1190
+ Returned value: ${(0, _prettyFormat.format)(returnedValue, {
1191
+ maxDepth: 3
1192
+ })}
1193
+ `;
1194
+ return reject(asyncError);
1195
+ }
1196
+ let errorAsErrorObject;
1197
+ if (checkIsError(reason)) {
1198
+ errorAsErrorObject = reason;
1199
+ } else {
1200
+ errorAsErrorObject = errorAtDone;
1201
+ errorAtDone.message = `Failed: ${(0, _prettyFormat.format)(reason, {
1202
+ maxDepth: 3
1203
+ })}`;
1204
+ }
1205
+
1206
+ // Consider always throwing, regardless if `reason` is set or not
1207
+ if (completed && reason) {
1208
+ errorAsErrorObject.message = `Caught error after test environment was torn down\n\n${errorAsErrorObject.message}`;
1209
+ throw errorAsErrorObject;
1210
+ }
1211
+ return reason ? reject(errorAsErrorObject) : resolve();
1212
+ });
1213
+ };
1214
+ returnedValue = fn.call(testContext, done);
1215
+ return;
1216
+ }
1217
+ let returnedValue;
1218
+ if (isGeneratorFunction(fn)) {
1219
+ returnedValue = _co.default.wrap(fn).call({});
1220
+ } else {
1221
+ try {
1222
+ returnedValue = fn.call(testContext);
1223
+ } catch (error) {
1224
+ reject(error);
1225
+ return;
1226
+ }
1227
+ }
1228
+ if ((0, _jestUtil.isPromise)(returnedValue)) {
1229
+ returnedValue.then(() => resolve(), reject);
1230
+ return;
1231
+ }
1232
+ if (!isHook && returnedValue !== undefined) {
1233
+ reject(new Error((0, _dedent.default)`
1234
+ test functions can only return Promise or undefined.
1235
+ Returned value: ${(0, _prettyFormat.format)(returnedValue, {
1236
+ maxDepth: 3
1237
+ })}
1238
+ `));
1239
+ return;
1240
+ }
1241
+
1242
+ // Otherwise this test is synchronous, and if it didn't throw it means
1243
+ // it passed.
1244
+ resolve();
1245
+ }).finally(() => {
1246
+ completed = true;
1247
+ // If timeout is not cleared/unrefed the node process won't exit until
1248
+ // it's resolved.
1249
+ timeoutID.unref?.();
1250
+ clearTimeout(timeoutID);
1251
+ });
1252
+ };
1253
+ exports.callAsyncCircusFn = callAsyncCircusFn;
1254
+ const getTestDuration = test => {
1255
+ const {
1256
+ startedAt
1257
+ } = test;
1258
+ return typeof startedAt === 'number' ? jestNow() - startedAt : null;
1259
+ };
1260
+ exports.getTestDuration = getTestDuration;
1261
+ const makeRunResult = (describeBlock, unhandledErrors) => ({
1262
+ testResults: makeTestResults(describeBlock),
1263
+ unhandledErrors: unhandledErrors.map(_getError).map(getErrorStack)
1264
+ });
1265
+ exports.makeRunResult = makeRunResult;
1266
+ const getTestNamesPath = test => {
1267
+ const titles = [];
1268
+ let parent = test;
1269
+ do {
1270
+ titles.unshift(parent.name);
1271
+ } while (parent = parent.parent);
1272
+ return titles;
1273
+ };
1274
+ const makeSingleTestResult = test => {
1275
+ const {
1276
+ includeTestLocationInResult
1277
+ } = (0, _state.getState)();
1278
+ const {
1279
+ status
1280
+ } = test;
1281
+ (0, _jestUtil.invariant)(status, 'Status should be present after tests are run.');
1282
+ const testPath = getTestNamesPath(test);
1283
+ let location = null;
1284
+ if (includeTestLocationInResult) {
1285
+ const stackLines = test.asyncError.stack.split('\n');
1286
+ const stackLine = stackLines[1];
1287
+ let parsedLine = stackUtils.parseLine(stackLine);
1288
+ if (parsedLine?.file?.startsWith(jestEachBuildDir)) {
1289
+ const stackLine = stackLines[2];
1290
+ parsedLine = stackUtils.parseLine(stackLine);
1291
+ }
1292
+ if (parsedLine && typeof parsedLine.column === 'number' && typeof parsedLine.line === 'number') {
1293
+ location = {
1294
+ column: parsedLine.column,
1295
+ line: parsedLine.line
1296
+ };
1297
+ }
1298
+ }
1299
+ const errorsDetailed = test.errors.map(_getError);
1300
+ return {
1301
+ duration: test.duration,
1302
+ errors: errorsDetailed.map(getErrorStack),
1303
+ errorsDetailed,
1304
+ failing: test.failing,
1305
+ invocations: test.invocations,
1306
+ location,
1307
+ numPassingAsserts: test.numPassingAsserts,
1308
+ retryReasons: test.retryReasons.map(_getError).map(getErrorStack),
1309
+ startedAt: test.startedAt,
1310
+ status,
1311
+ testPath: [...testPath]
1312
+ };
1313
+ };
1314
+ exports.makeSingleTestResult = makeSingleTestResult;
1315
+ const makeTestResults = describeBlock => {
1316
+ const testResults = [];
1317
+ const stack = [[describeBlock, 0]];
1318
+ while (stack.length > 0) {
1319
+ const [currentBlock, childIndex] = stack.pop();
1320
+ for (let i = childIndex; i < currentBlock.children.length; i++) {
1321
+ const child = currentBlock.children[i];
1322
+ if (child.type === 'describeBlock') {
1323
+ stack.push([currentBlock, i + 1], [child, 0]);
1324
+ break;
1325
+ }
1326
+ if (child.type === 'test') {
1327
+ testResults.push(makeSingleTestResult(child));
1328
+ }
1329
+ }
1330
+ }
1331
+ return testResults;
1332
+ };
1333
+
1334
+ // Return a string that identifies the test (concat of parent describe block
1335
+ // names + test title)
1336
+ const getTestID = test => {
1337
+ const testNamesPath = getTestNamesPath(test);
1338
+ testNamesPath.shift(); // remove TOP_DESCRIBE_BLOCK_NAME
1339
+ return testNamesPath.join(' ');
1340
+ };
1341
+ exports.getTestID = getTestID;
1342
+ const _getError = errors => {
1343
+ let error;
1344
+ let asyncError;
1345
+ if (Array.isArray(errors)) {
1346
+ error = errors[0];
1347
+ asyncError = errors[1];
1348
+ } else {
1349
+ error = errors;
1350
+ // eslint-disable-next-line unicorn/error-message
1351
+ asyncError = new Error();
1352
+ }
1353
+ if (error && (typeof error.stack === 'string' || error.message)) {
1354
+ return error;
1355
+ }
1356
+ asyncError.message = `thrown: ${(0, _prettyFormat.format)(error, {
1357
+ maxDepth: 3
1358
+ })}`;
1359
+ return asyncError;
1360
+ };
1361
+ const getErrorStack = error => typeof error.stack === 'string' && error.stack !== '' ? error.stack : error.message;
1362
+ const addErrorToEachTestUnderDescribe = (describeBlock, error, asyncError) => {
1363
+ for (const child of describeBlock.children) {
1364
+ switch (child.type) {
1365
+ case 'describeBlock':
1366
+ addErrorToEachTestUnderDescribe(child, error, asyncError);
1367
+ break;
1368
+ case 'test':
1369
+ child.errors.push([error, asyncError]);
1370
+ break;
1371
+ }
1372
+ }
1373
+ };
1374
+ exports.addErrorToEachTestUnderDescribe = addErrorToEachTestUnderDescribe;
1375
+ const resolveTestCaseStartInfo = testNamesPath => {
1376
+ const ancestorTitles = testNamesPath.filter(name => name !== _state.ROOT_DESCRIBE_BLOCK_NAME);
1377
+ const fullName = ancestorTitles.join(' ');
1378
+ const title = testNamesPath.at(-1);
1379
+ // remove title
1380
+ ancestorTitles.pop();
1381
+ return {
1382
+ ancestorTitles,
1383
+ fullName,
1384
+ title
1385
+ };
1386
+ };
1387
+ const parseSingleTestResult = testResult => {
1388
+ let status;
1389
+ if (testResult.status === 'skip') {
1390
+ status = 'pending';
1391
+ } else if (testResult.status === 'todo') {
1392
+ status = 'todo';
1393
+ } else if (testResult.errors.length > 0) {
1394
+ status = 'failed';
1395
+ } else {
1396
+ status = 'passed';
1397
+ }
1398
+ const {
1399
+ ancestorTitles,
1400
+ fullName,
1401
+ title
1402
+ } = resolveTestCaseStartInfo(testResult.testPath);
1403
+ return {
1404
+ ancestorTitles,
1405
+ duration: testResult.duration,
1406
+ failing: testResult.failing,
1407
+ failureDetails: testResult.errorsDetailed,
1408
+ failureMessages: [...testResult.errors],
1409
+ fullName,
1410
+ invocations: testResult.invocations,
1411
+ location: testResult.location,
1412
+ numPassingAsserts: testResult.numPassingAsserts,
1413
+ retryReasons: [...testResult.retryReasons],
1414
+ startedAt: testResult.startedAt,
1415
+ status,
1416
+ title
1417
+ };
1418
+ };
1419
+ exports.parseSingleTestResult = parseSingleTestResult;
1420
+ const createTestCaseStartInfo = test => {
1421
+ const testPath = getTestNamesPath(test);
1422
+ const {
1423
+ ancestorTitles,
1424
+ fullName,
1425
+ title
1426
+ } = resolveTestCaseStartInfo(testPath);
1427
+ return {
1428
+ ancestorTitles,
1429
+ fullName,
1430
+ mode: test.mode,
1431
+ startedAt: test.startedAt,
1432
+ title
1433
+ };
1434
+ };
1435
+ exports.createTestCaseStartInfo = createTestCaseStartInfo;
1436
+
1437
+ /***/ }
1438
+
1439
+ /******/ });
1440
+ /************************************************************************/
1441
+ /******/ // The module cache
1442
+ /******/ var __webpack_module_cache__ = {};
1443
+ /******/
1444
+ /******/ // The require function
1445
+ /******/ function __webpack_require__(moduleId) {
1446
+ /******/ // Check if module is in cache
1447
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
1448
+ /******/ if (cachedModule !== undefined) {
1449
+ /******/ return cachedModule.exports;
1450
+ /******/ }
1451
+ /******/ // Create a new module (and put it into the cache)
1452
+ /******/ var module = __webpack_module_cache__[moduleId] = {
1453
+ /******/ // no module.id needed
1454
+ /******/ // no module.loaded needed
1455
+ /******/ exports: {}
1456
+ /******/ };
1457
+ /******/
1458
+ /******/ // Execute the module function
1459
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
1460
+ /******/
1461
+ /******/ // Return the exports of the module
1462
+ /******/ return module.exports;
1463
+ /******/ }
1464
+ /******/
1465
+ /************************************************************************/
1466
+ var __webpack_exports__ = {};
1467
+ // This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
1468
+ (() => {
1469
+ var exports = __webpack_exports__;
1470
+
1471
+
1472
+ Object.defineProperty(exports, "__esModule", ({
1473
+ value: true
1474
+ }));
1475
+ Object.defineProperty(exports, "addEventHandler", ({
1476
+ enumerable: true,
1477
+ get: function () {
1478
+ return _state.addEventHandler;
1479
+ }
1480
+ }));
1481
+ exports.describe = exports["default"] = exports.beforeEach = exports.beforeAll = exports.afterEach = exports.afterAll = void 0;
1482
+ Object.defineProperty(exports, "getState", ({
1483
+ enumerable: true,
1484
+ get: function () {
1485
+ return _state.getState;
1486
+ }
1487
+ }));
1488
+ exports.it = void 0;
1489
+ Object.defineProperty(exports, "removeEventHandler", ({
1490
+ enumerable: true,
1491
+ get: function () {
1492
+ return _state.removeEventHandler;
1493
+ }
1494
+ }));
1495
+ Object.defineProperty(exports, "resetState", ({
1496
+ enumerable: true,
1497
+ get: function () {
1498
+ return _state.resetState;
1499
+ }
1500
+ }));
1501
+ Object.defineProperty(exports, "run", ({
1502
+ enumerable: true,
1503
+ get: function () {
1504
+ return _run.default;
1505
+ }
1506
+ }));
1507
+ Object.defineProperty(exports, "setState", ({
1508
+ enumerable: true,
1509
+ get: function () {
1510
+ return _state.setState;
1511
+ }
1512
+ }));
1513
+ exports.test = void 0;
1514
+ var _jestEach = require("jest-each");
1515
+ var _jestUtil = require("jest-util");
1516
+ var _state = __webpack_require__("./src/state.ts");
1517
+ var _run = _interopRequireDefault(__webpack_require__("./src/run.ts"));
1518
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1519
+ /**
1520
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1521
+ *
1522
+ * This source code is licensed under the MIT license found in the
1523
+ * LICENSE file in the root directory of this source tree.
1524
+ */
1525
+
1526
+ const describe = exports.describe = (() => {
1527
+ const describe = (blockName, blockFn) => _dispatchDescribe(blockFn, blockName, describe);
1528
+ const only = (blockName, blockFn) => _dispatchDescribe(blockFn, blockName, only, 'only');
1529
+ const skip = (blockName, blockFn) => _dispatchDescribe(blockFn, blockName, skip, 'skip');
1530
+ describe.each = (0, _jestEach.bind)(describe, false);
1531
+ only.each = (0, _jestEach.bind)(only, false);
1532
+ skip.each = (0, _jestEach.bind)(skip, false);
1533
+ describe.only = only;
1534
+ describe.skip = skip;
1535
+ return describe;
1536
+ })();
1537
+ const _dispatchDescribe = (blockFn, blockName, describeFn, mode) => {
1538
+ const asyncError = new _jestUtil.ErrorWithStack(undefined, describeFn);
1539
+ if (blockFn === undefined) {
1540
+ asyncError.message = 'Missing second argument. It must be a callback function.';
1541
+ throw asyncError;
1542
+ }
1543
+ if (typeof blockFn !== 'function') {
1544
+ asyncError.message = `Invalid second argument, ${blockFn}. It must be a callback function.`;
1545
+ throw asyncError;
1546
+ }
1547
+ try {
1548
+ blockName = (0, _jestUtil.convertDescriptorToString)(blockName);
1549
+ } catch (error) {
1550
+ asyncError.message = error.message;
1551
+ throw asyncError;
1552
+ }
1553
+ (0, _state.dispatchSync)({
1554
+ asyncError,
1555
+ blockName,
1556
+ mode,
1557
+ name: 'start_describe_definition'
1558
+ });
1559
+ const describeReturn = blockFn();
1560
+ if ((0, _jestUtil.isPromise)(describeReturn)) {
1561
+ throw new _jestUtil.ErrorWithStack('Returning a Promise from "describe" is not supported. Tests must be defined synchronously.', describeFn);
1562
+ } else if (describeReturn !== undefined) {
1563
+ throw new _jestUtil.ErrorWithStack('A "describe" callback must not return a value.', describeFn);
1564
+ }
1565
+ (0, _state.dispatchSync)({
1566
+ blockName,
1567
+ mode,
1568
+ name: 'finish_describe_definition'
1569
+ });
1570
+ };
1571
+ const _addHook = (fn, hookType, hookFn, timeout) => {
1572
+ const asyncError = new _jestUtil.ErrorWithStack(undefined, hookFn);
1573
+ if (typeof fn !== 'function') {
1574
+ asyncError.message = 'Invalid first argument. It must be a callback function.';
1575
+ throw asyncError;
1576
+ }
1577
+ (0, _state.dispatchSync)({
1578
+ asyncError,
1579
+ fn,
1580
+ hookType,
1581
+ name: 'add_hook',
1582
+ timeout
1583
+ });
1584
+ };
1585
+
1586
+ // Hooks have to pass themselves to the HOF in order for us to trim stack traces.
1587
+ const beforeEach = (fn, timeout) => _addHook(fn, 'beforeEach', beforeEach, timeout);
1588
+ exports.beforeEach = beforeEach;
1589
+ const beforeAll = (fn, timeout) => _addHook(fn, 'beforeAll', beforeAll, timeout);
1590
+ exports.beforeAll = beforeAll;
1591
+ const afterEach = (fn, timeout) => _addHook(fn, 'afterEach', afterEach, timeout);
1592
+ exports.afterEach = afterEach;
1593
+ const afterAll = (fn, timeout) => _addHook(fn, 'afterAll', afterAll, timeout);
1594
+ exports.afterAll = afterAll;
1595
+ const test = exports.test = (() => {
1596
+ const test = (testName, fn, timeout) => _addTest(testName, undefined, false, fn, test, timeout);
1597
+ const skip = (testName, fn, timeout) => _addTest(testName, 'skip', false, fn, skip, timeout);
1598
+ const only = (testName, fn, timeout) => _addTest(testName, 'only', false, fn, test.only, timeout);
1599
+ const concurrentTest = (testName, fn, timeout) => _addTest(testName, undefined, true, fn, concurrentTest, timeout);
1600
+ const concurrentOnly = (testName, fn, timeout) => _addTest(testName, 'only', true, fn, concurrentOnly, timeout);
1601
+ const bindFailing = (concurrent, mode) => {
1602
+ const failing = (testName, fn, timeout, eachError) => _addTest(testName, mode, concurrent, fn, failing, timeout, true, eachError);
1603
+ failing.each = (0, _jestEach.bind)(failing, false, true);
1604
+ return failing;
1605
+ };
1606
+ test.todo = (testName, ...rest) => {
1607
+ if (rest.length > 0 || typeof testName !== 'string') {
1608
+ throw new _jestUtil.ErrorWithStack('Todo must be called with only a description.', test.todo);
1609
+ }
1610
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
1611
+ return _addTest(testName, 'todo', false, () => {}, test.todo);
1612
+ };
1613
+ const _addTest = (testName, mode, concurrent, fn, testFn, timeout, failing, asyncError = new _jestUtil.ErrorWithStack(undefined, testFn)) => {
1614
+ try {
1615
+ testName = (0, _jestUtil.convertDescriptorToString)(testName);
1616
+ } catch (error) {
1617
+ asyncError.message = error.message;
1618
+ throw asyncError;
1619
+ }
1620
+ if (fn === undefined) {
1621
+ asyncError.message = 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.';
1622
+ throw asyncError;
1623
+ }
1624
+ if (typeof fn !== 'function') {
1625
+ asyncError.message = `Invalid second argument, ${fn}. It must be a callback function.`;
1626
+ throw asyncError;
1627
+ }
1628
+ return (0, _state.dispatchSync)({
1629
+ asyncError,
1630
+ concurrent,
1631
+ failing: failing === undefined ? false : failing,
1632
+ fn,
1633
+ mode,
1634
+ name: 'add_test',
1635
+ testName,
1636
+ timeout
1637
+ });
1638
+ };
1639
+ test.each = (0, _jestEach.bind)(test);
1640
+ only.each = (0, _jestEach.bind)(only);
1641
+ skip.each = (0, _jestEach.bind)(skip);
1642
+ concurrentTest.each = (0, _jestEach.bind)(concurrentTest, false);
1643
+ concurrentOnly.each = (0, _jestEach.bind)(concurrentOnly, false);
1644
+ only.failing = bindFailing(false, 'only');
1645
+ skip.failing = bindFailing(false, 'skip');
1646
+ test.failing = bindFailing(false);
1647
+ test.only = only;
1648
+ test.skip = skip;
1649
+ test.concurrent = concurrentTest;
1650
+ concurrentTest.only = concurrentOnly;
1651
+ concurrentTest.skip = skip;
1652
+ concurrentTest.failing = bindFailing(true);
1653
+ concurrentOnly.failing = bindFailing(true, 'only');
1654
+ return test;
1655
+ })();
1656
+ const it = exports.it = test;
1657
+ var _default = exports["default"] = {
1658
+ afterAll,
1659
+ afterEach,
1660
+ beforeAll,
1661
+ beforeEach,
1662
+ describe,
1663
+ it,
1664
+ test
1665
+ };
1666
+ })();
1667
+
1668
+ module.exports = __webpack_exports__;
1669
+ /******/ })()
1670
+ ;