@vitest/runner 3.2.0-beta.2 → 3.2.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,2243 @@
1
+ import { isObject, createDefer, toArray, isNegativeNaN, format, objectAttr, objDisplay, shuffle, getSafeTimers, assertTypes } from '@vitest/utils';
2
+ import { parseSingleStack } from '@vitest/utils/source-map';
3
+ import { processError } from '@vitest/utils/error';
4
+ import { relative } from 'pathe';
5
+
6
+ class PendingError extends Error {
7
+ code = "VITEST_PENDING";
8
+ taskId;
9
+ constructor(message, task, note) {
10
+ super(message);
11
+ this.message = message;
12
+ this.note = note;
13
+ this.taskId = task.id;
14
+ }
15
+ }
16
+ class TestRunAbortError extends Error {
17
+ name = "TestRunAbortError";
18
+ reason;
19
+ constructor(message, reason) {
20
+ super(message);
21
+ this.reason = reason;
22
+ }
23
+ }
24
+
25
+ // use WeakMap here to make the Test and Suite object serializable
26
+ const fnMap = new WeakMap();
27
+ const testFixtureMap = new WeakMap();
28
+ const hooksMap = new WeakMap();
29
+ function setFn(key, fn) {
30
+ fnMap.set(key, fn);
31
+ }
32
+ function getFn(key) {
33
+ return fnMap.get(key);
34
+ }
35
+ function setTestFixture(key, fixture) {
36
+ testFixtureMap.set(key, fixture);
37
+ }
38
+ function getTestFixture(key) {
39
+ return testFixtureMap.get(key);
40
+ }
41
+ function setHooks(key, hooks) {
42
+ hooksMap.set(key, hooks);
43
+ }
44
+ function getHooks(key) {
45
+ return hooksMap.get(key);
46
+ }
47
+
48
+ async function runSetupFiles(config, files, runner) {
49
+ if (config.sequence.setupFiles === "parallel") {
50
+ await Promise.all(files.map(async (fsPath) => {
51
+ await runner.importFile(fsPath, "setup");
52
+ }));
53
+ } else {
54
+ for (const fsPath of files) {
55
+ await runner.importFile(fsPath, "setup");
56
+ }
57
+ }
58
+ }
59
+
60
+ function mergeScopedFixtures(testFixtures, scopedFixtures) {
61
+ const scopedFixturesMap = scopedFixtures.reduce((map, fixture) => {
62
+ map[fixture.prop] = fixture;
63
+ return map;
64
+ }, {});
65
+ const newFixtures = {};
66
+ testFixtures.forEach((fixture) => {
67
+ const useFixture = scopedFixturesMap[fixture.prop] || { ...fixture };
68
+ newFixtures[useFixture.prop] = useFixture;
69
+ });
70
+ for (const fixtureKep in newFixtures) {
71
+ var _fixture$deps;
72
+ const fixture = newFixtures[fixtureKep];
73
+ // if the fixture was define before the scope, then its dep
74
+ // will reference the original fixture instead of the scope
75
+ fixture.deps = (_fixture$deps = fixture.deps) === null || _fixture$deps === void 0 ? void 0 : _fixture$deps.map((dep) => newFixtures[dep.prop]);
76
+ }
77
+ return Object.values(newFixtures);
78
+ }
79
+ function mergeContextFixtures(fixtures, context, runner) {
80
+ const fixtureOptionKeys = [
81
+ "auto",
82
+ "injected",
83
+ "scope"
84
+ ];
85
+ const fixtureArray = Object.entries(fixtures).map(([prop, value]) => {
86
+ const fixtureItem = { value };
87
+ if (Array.isArray(value) && value.length >= 2 && isObject(value[1]) && Object.keys(value[1]).some((key) => fixtureOptionKeys.includes(key))) {
88
+ var _runner$injectValue;
89
+ // fixture with options
90
+ Object.assign(fixtureItem, value[1]);
91
+ const userValue = value[0];
92
+ fixtureItem.value = fixtureItem.injected ? ((_runner$injectValue = runner.injectValue) === null || _runner$injectValue === void 0 ? void 0 : _runner$injectValue.call(runner, prop)) ?? userValue : userValue;
93
+ }
94
+ fixtureItem.scope = fixtureItem.scope || "test";
95
+ if (fixtureItem.scope === "worker" && !runner.getWorkerContext) {
96
+ fixtureItem.scope = "file";
97
+ }
98
+ fixtureItem.prop = prop;
99
+ fixtureItem.isFn = typeof fixtureItem.value === "function";
100
+ return fixtureItem;
101
+ });
102
+ if (Array.isArray(context.fixtures)) {
103
+ context.fixtures = context.fixtures.concat(fixtureArray);
104
+ } else {
105
+ context.fixtures = fixtureArray;
106
+ }
107
+ // Update dependencies of fixture functions
108
+ fixtureArray.forEach((fixture) => {
109
+ if (fixture.isFn) {
110
+ const usedProps = getUsedProps(fixture.value);
111
+ if (usedProps.length) {
112
+ fixture.deps = context.fixtures.filter(({ prop }) => prop !== fixture.prop && usedProps.includes(prop));
113
+ }
114
+ // test can access anything, so we ignore it
115
+ if (fixture.scope !== "test") {
116
+ var _fixture$deps2;
117
+ (_fixture$deps2 = fixture.deps) === null || _fixture$deps2 === void 0 ? void 0 : _fixture$deps2.forEach((dep) => {
118
+ if (!dep.isFn) {
119
+ // non fn fixtures are always resolved and available to anyone
120
+ return;
121
+ }
122
+ // worker scope can only import from worker scope
123
+ if (fixture.scope === "worker" && dep.scope === "worker") {
124
+ return;
125
+ }
126
+ // file scope an import from file and worker scopes
127
+ if (fixture.scope === "file" && dep.scope !== "test") {
128
+ return;
129
+ }
130
+ throw new SyntaxError(`cannot use the ${dep.scope} fixture "${dep.prop}" inside the ${fixture.scope} fixture "${fixture.prop}"`);
131
+ });
132
+ }
133
+ }
134
+ });
135
+ return context;
136
+ }
137
+ const fixtureValueMaps = new Map();
138
+ const cleanupFnArrayMap = new Map();
139
+ async function callFixtureCleanup(context) {
140
+ const cleanupFnArray = cleanupFnArrayMap.get(context) ?? [];
141
+ for (const cleanup of cleanupFnArray.reverse()) {
142
+ await cleanup();
143
+ }
144
+ cleanupFnArrayMap.delete(context);
145
+ }
146
+ function withFixtures(runner, fn, testContext) {
147
+ return (hookContext) => {
148
+ const context = hookContext || testContext;
149
+ if (!context) {
150
+ return fn({});
151
+ }
152
+ const fixtures = getTestFixture(context);
153
+ if (!(fixtures === null || fixtures === void 0 ? void 0 : fixtures.length)) {
154
+ return fn(context);
155
+ }
156
+ const usedProps = getUsedProps(fn);
157
+ const hasAutoFixture = fixtures.some(({ auto }) => auto);
158
+ if (!usedProps.length && !hasAutoFixture) {
159
+ return fn(context);
160
+ }
161
+ if (!fixtureValueMaps.get(context)) {
162
+ fixtureValueMaps.set(context, new Map());
163
+ }
164
+ const fixtureValueMap = fixtureValueMaps.get(context);
165
+ if (!cleanupFnArrayMap.has(context)) {
166
+ cleanupFnArrayMap.set(context, []);
167
+ }
168
+ const cleanupFnArray = cleanupFnArrayMap.get(context);
169
+ const usedFixtures = fixtures.filter(({ prop, auto }) => auto || usedProps.includes(prop));
170
+ const pendingFixtures = resolveDeps(usedFixtures);
171
+ if (!pendingFixtures.length) {
172
+ return fn(context);
173
+ }
174
+ async function resolveFixtures() {
175
+ for (const fixture of pendingFixtures) {
176
+ // fixture could be already initialized during "before" hook
177
+ if (fixtureValueMap.has(fixture)) {
178
+ continue;
179
+ }
180
+ const resolvedValue = await resolveFixtureValue(runner, fixture, context, cleanupFnArray);
181
+ context[fixture.prop] = resolvedValue;
182
+ fixtureValueMap.set(fixture, resolvedValue);
183
+ if (fixture.scope === "test") {
184
+ cleanupFnArray.unshift(() => {
185
+ fixtureValueMap.delete(fixture);
186
+ });
187
+ }
188
+ }
189
+ }
190
+ return resolveFixtures().then(() => fn(context));
191
+ };
192
+ }
193
+ const globalFixturePromise = new WeakMap();
194
+ function resolveFixtureValue(runner, fixture, context, cleanupFnArray) {
195
+ var _runner$getWorkerCont;
196
+ const fileContext = getFileContext(context.task.file);
197
+ const workerContext = (_runner$getWorkerCont = runner.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner);
198
+ if (!fixture.isFn) {
199
+ var _fixture$prop;
200
+ fileContext[_fixture$prop = fixture.prop] ?? (fileContext[_fixture$prop] = fixture.value);
201
+ if (workerContext) {
202
+ var _fixture$prop2;
203
+ workerContext[_fixture$prop2 = fixture.prop] ?? (workerContext[_fixture$prop2] = fixture.value);
204
+ }
205
+ return fixture.value;
206
+ }
207
+ if (fixture.scope === "test") {
208
+ return resolveFixtureFunction(fixture.value, context, cleanupFnArray);
209
+ }
210
+ // in case the test runs in parallel
211
+ if (globalFixturePromise.has(fixture)) {
212
+ return globalFixturePromise.get(fixture);
213
+ }
214
+ let fixtureContext;
215
+ if (fixture.scope === "worker") {
216
+ if (!workerContext) {
217
+ throw new TypeError("[@vitest/runner] The worker context is not available in the current test runner. Please, provide the `getWorkerContext` method when initiating the runner.");
218
+ }
219
+ fixtureContext = workerContext;
220
+ } else {
221
+ fixtureContext = fileContext;
222
+ }
223
+ if (fixture.prop in fixtureContext) {
224
+ return fixtureContext[fixture.prop];
225
+ }
226
+ if (!cleanupFnArrayMap.has(fixtureContext)) {
227
+ cleanupFnArrayMap.set(fixtureContext, []);
228
+ }
229
+ const cleanupFnFileArray = cleanupFnArrayMap.get(fixtureContext);
230
+ const promise = resolveFixtureFunction(fixture.value, fixtureContext, cleanupFnFileArray).then((value) => {
231
+ fixtureContext[fixture.prop] = value;
232
+ globalFixturePromise.delete(fixture);
233
+ return value;
234
+ });
235
+ globalFixturePromise.set(fixture, promise);
236
+ return promise;
237
+ }
238
+ async function resolveFixtureFunction(fixtureFn, context, cleanupFnArray) {
239
+ // wait for `use` call to extract fixture value
240
+ const useFnArgPromise = createDefer();
241
+ let isUseFnArgResolved = false;
242
+ const fixtureReturn = fixtureFn(context, async (useFnArg) => {
243
+ // extract `use` argument
244
+ isUseFnArgResolved = true;
245
+ useFnArgPromise.resolve(useFnArg);
246
+ // suspend fixture teardown by holding off `useReturnPromise` resolution until cleanup
247
+ const useReturnPromise = createDefer();
248
+ cleanupFnArray.push(async () => {
249
+ // start teardown by resolving `use` Promise
250
+ useReturnPromise.resolve();
251
+ // wait for finishing teardown
252
+ await fixtureReturn;
253
+ });
254
+ await useReturnPromise;
255
+ }).catch((e) => {
256
+ // treat fixture setup error as test failure
257
+ if (!isUseFnArgResolved) {
258
+ useFnArgPromise.reject(e);
259
+ return;
260
+ }
261
+ // otherwise re-throw to avoid silencing error during cleanup
262
+ throw e;
263
+ });
264
+ return useFnArgPromise;
265
+ }
266
+ function resolveDeps(fixtures, depSet = new Set(), pendingFixtures = []) {
267
+ fixtures.forEach((fixture) => {
268
+ if (pendingFixtures.includes(fixture)) {
269
+ return;
270
+ }
271
+ if (!fixture.isFn || !fixture.deps) {
272
+ pendingFixtures.push(fixture);
273
+ return;
274
+ }
275
+ if (depSet.has(fixture)) {
276
+ throw new Error(`Circular fixture dependency detected: ${fixture.prop} <- ${[...depSet].reverse().map((d) => d.prop).join(" <- ")}`);
277
+ }
278
+ depSet.add(fixture);
279
+ resolveDeps(fixture.deps, depSet, pendingFixtures);
280
+ pendingFixtures.push(fixture);
281
+ depSet.clear();
282
+ });
283
+ return pendingFixtures;
284
+ }
285
+ function getUsedProps(fn) {
286
+ let fnString = fn.toString();
287
+ // match lowered async function and strip it off
288
+ // example code on esbuild-try https://esbuild.github.io/try/#YgAwLjI0LjAALS1zdXBwb3J0ZWQ6YXN5bmMtYXdhaXQ9ZmFsc2UAZQBlbnRyeS50cwBjb25zdCBvID0gewogIGYxOiBhc3luYyAoKSA9PiB7fSwKICBmMjogYXN5bmMgKGEpID0+IHt9LAogIGYzOiBhc3luYyAoYSwgYikgPT4ge30sCiAgZjQ6IGFzeW5jIGZ1bmN0aW9uKGEpIHt9LAogIGY1OiBhc3luYyBmdW5jdGlvbiBmZihhKSB7fSwKICBhc3luYyBmNihhKSB7fSwKCiAgZzE6IGFzeW5jICgpID0+IHt9LAogIGcyOiBhc3luYyAoeyBhIH0pID0+IHt9LAogIGczOiBhc3luYyAoeyBhIH0sIGIpID0+IHt9LAogIGc0OiBhc3luYyBmdW5jdGlvbiAoeyBhIH0pIHt9LAogIGc1OiBhc3luYyBmdW5jdGlvbiBnZyh7IGEgfSkge30sCiAgYXN5bmMgZzYoeyBhIH0pIHt9Cn0
289
+ // __async(this, null, function*
290
+ // __async(this, arguments, function*
291
+ // __async(this, [_0, _1], function*
292
+ if (/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString)) {
293
+ fnString = fnString.split(/__async\((?:this|null),/)[1];
294
+ }
295
+ const match = fnString.match(/[^(]*\(([^)]*)/);
296
+ if (!match) {
297
+ return [];
298
+ }
299
+ const args = splitByComma(match[1]);
300
+ if (!args.length) {
301
+ return [];
302
+ }
303
+ let first = args[0];
304
+ if ("__VITEST_FIXTURE_INDEX__" in fn) {
305
+ first = args[fn.__VITEST_FIXTURE_INDEX__];
306
+ if (!first) {
307
+ return [];
308
+ }
309
+ }
310
+ if (!(first.startsWith("{") && first.endsWith("}"))) {
311
+ throw new Error(`The first argument inside a fixture must use object destructuring pattern, e.g. ({ test } => {}). Instead, received "${first}".`);
312
+ }
313
+ const _first = first.slice(1, -1).replace(/\s/g, "");
314
+ const props = splitByComma(_first).map((prop) => {
315
+ return prop.replace(/:.*|=.*/g, "");
316
+ });
317
+ const last = props.at(-1);
318
+ if (last && last.startsWith("...")) {
319
+ throw new Error(`Rest parameters are not supported in fixtures, received "${last}".`);
320
+ }
321
+ return props;
322
+ }
323
+ function splitByComma(s) {
324
+ const result = [];
325
+ const stack = [];
326
+ let start = 0;
327
+ for (let i = 0; i < s.length; i++) {
328
+ if (s[i] === "{" || s[i] === "[") {
329
+ stack.push(s[i] === "{" ? "}" : "]");
330
+ } else if (s[i] === stack[stack.length - 1]) {
331
+ stack.pop();
332
+ } else if (!stack.length && s[i] === ",") {
333
+ const token = s.substring(start, i).trim();
334
+ if (token) {
335
+ result.push(token);
336
+ }
337
+ start = i + 1;
338
+ }
339
+ }
340
+ const lastToken = s.substring(start).trim();
341
+ if (lastToken) {
342
+ result.push(lastToken);
343
+ }
344
+ return result;
345
+ }
346
+
347
+ let _test;
348
+ function setCurrentTest(test) {
349
+ _test = test;
350
+ }
351
+ function getCurrentTest() {
352
+ return _test;
353
+ }
354
+ const tests = [];
355
+ function addRunningTest(test) {
356
+ tests.push(test);
357
+ return () => {
358
+ tests.splice(tests.indexOf(test));
359
+ };
360
+ }
361
+ function getRunningTests() {
362
+ return tests;
363
+ }
364
+
365
+ function createChainable(keys, fn) {
366
+ function create(context) {
367
+ const chain = function(...args) {
368
+ return fn.apply(context, args);
369
+ };
370
+ Object.assign(chain, fn);
371
+ chain.withContext = () => chain.bind(context);
372
+ chain.setContext = (key, value) => {
373
+ context[key] = value;
374
+ };
375
+ chain.mergeContext = (ctx) => {
376
+ Object.assign(context, ctx);
377
+ };
378
+ for (const key of keys) {
379
+ Object.defineProperty(chain, key, { get() {
380
+ return create({
381
+ ...context,
382
+ [key]: true
383
+ });
384
+ } });
385
+ }
386
+ return chain;
387
+ }
388
+ const chain = create({});
389
+ chain.fn = fn;
390
+ return chain;
391
+ }
392
+
393
+ /**
394
+ * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
395
+ * Suites can contain both tests and other suites, enabling complex test structures.
396
+ *
397
+ * @param {string} name - The name of the suite, used for identification and reporting.
398
+ * @param {Function} fn - A function that defines the tests and suites within this suite.
399
+ * @example
400
+ * ```ts
401
+ * // Define a suite with two tests
402
+ * suite('Math operations', () => {
403
+ * test('should add two numbers', () => {
404
+ * expect(add(1, 2)).toBe(3);
405
+ * });
406
+ *
407
+ * test('should subtract two numbers', () => {
408
+ * expect(subtract(5, 2)).toBe(3);
409
+ * });
410
+ * });
411
+ * ```
412
+ * @example
413
+ * ```ts
414
+ * // Define nested suites
415
+ * suite('String operations', () => {
416
+ * suite('Trimming', () => {
417
+ * test('should trim whitespace from start and end', () => {
418
+ * expect(' hello '.trim()).toBe('hello');
419
+ * });
420
+ * });
421
+ *
422
+ * suite('Concatenation', () => {
423
+ * test('should concatenate two strings', () => {
424
+ * expect('hello' + ' ' + 'world').toBe('hello world');
425
+ * });
426
+ * });
427
+ * });
428
+ * ```
429
+ */
430
+ const suite = createSuite();
431
+ /**
432
+ * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
433
+ *
434
+ * @param {string | Function} name - The name of the test or a function that will be used as a test name.
435
+ * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
436
+ * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
437
+ * @throws {Error} If called inside another test function.
438
+ * @example
439
+ * ```ts
440
+ * // Define a simple test
441
+ * test('should add two numbers', () => {
442
+ * expect(add(1, 2)).toBe(3);
443
+ * });
444
+ * ```
445
+ * @example
446
+ * ```ts
447
+ * // Define a test with options
448
+ * test('should subtract two numbers', { retry: 3 }, () => {
449
+ * expect(subtract(5, 2)).toBe(3);
450
+ * });
451
+ * ```
452
+ */
453
+ const test = createTest(function(name, optionsOrFn, optionsOrTest) {
454
+ if (getCurrentTest()) {
455
+ throw new Error("Calling the test function inside another test function is not allowed. Please put it inside \"describe\" or \"suite\" so it can be properly collected.");
456
+ }
457
+ getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
458
+ });
459
+ /**
460
+ * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
461
+ * Suites can contain both tests and other suites, enabling complex test structures.
462
+ *
463
+ * @param {string} name - The name of the suite, used for identification and reporting.
464
+ * @param {Function} fn - A function that defines the tests and suites within this suite.
465
+ * @example
466
+ * ```ts
467
+ * // Define a suite with two tests
468
+ * describe('Math operations', () => {
469
+ * test('should add two numbers', () => {
470
+ * expect(add(1, 2)).toBe(3);
471
+ * });
472
+ *
473
+ * test('should subtract two numbers', () => {
474
+ * expect(subtract(5, 2)).toBe(3);
475
+ * });
476
+ * });
477
+ * ```
478
+ * @example
479
+ * ```ts
480
+ * // Define nested suites
481
+ * describe('String operations', () => {
482
+ * describe('Trimming', () => {
483
+ * test('should trim whitespace from start and end', () => {
484
+ * expect(' hello '.trim()).toBe('hello');
485
+ * });
486
+ * });
487
+ *
488
+ * describe('Concatenation', () => {
489
+ * test('should concatenate two strings', () => {
490
+ * expect('hello' + ' ' + 'world').toBe('hello world');
491
+ * });
492
+ * });
493
+ * });
494
+ * ```
495
+ */
496
+ const describe = suite;
497
+ /**
498
+ * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
499
+ *
500
+ * @param {string | Function} name - The name of the test or a function that will be used as a test name.
501
+ * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
502
+ * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
503
+ * @throws {Error} If called inside another test function.
504
+ * @example
505
+ * ```ts
506
+ * // Define a simple test
507
+ * it('adds two numbers', () => {
508
+ * expect(add(1, 2)).toBe(3);
509
+ * });
510
+ * ```
511
+ * @example
512
+ * ```ts
513
+ * // Define a test with options
514
+ * it('subtracts two numbers', { retry: 3 }, () => {
515
+ * expect(subtract(5, 2)).toBe(3);
516
+ * });
517
+ * ```
518
+ */
519
+ const it = test;
520
+ let runner;
521
+ let defaultSuite;
522
+ let currentTestFilepath;
523
+ function assert(condition, message) {
524
+ if (!condition) {
525
+ throw new Error(`Vitest failed to find ${message}. This is a bug in Vitest. Please, open an issue with reproduction.`);
526
+ }
527
+ }
528
+ function getDefaultSuite() {
529
+ assert(defaultSuite, "the default suite");
530
+ return defaultSuite;
531
+ }
532
+ function getTestFilepath() {
533
+ return currentTestFilepath;
534
+ }
535
+ function getRunner() {
536
+ assert(runner, "the runner");
537
+ return runner;
538
+ }
539
+ function createDefaultSuite(runner) {
540
+ const config = runner.config.sequence;
541
+ const collector = suite("", { concurrent: config.concurrent }, () => {});
542
+ // no parent suite for top-level tests
543
+ delete collector.suite;
544
+ return collector;
545
+ }
546
+ function clearCollectorContext(filepath, currentRunner) {
547
+ if (!defaultSuite) {
548
+ defaultSuite = createDefaultSuite(currentRunner);
549
+ }
550
+ runner = currentRunner;
551
+ currentTestFilepath = filepath;
552
+ collectorContext.tasks.length = 0;
553
+ defaultSuite.clear();
554
+ collectorContext.currentSuite = defaultSuite;
555
+ }
556
+ function getCurrentSuite() {
557
+ const currentSuite = collectorContext.currentSuite || defaultSuite;
558
+ assert(currentSuite, "the current suite");
559
+ return currentSuite;
560
+ }
561
+ function createSuiteHooks() {
562
+ return {
563
+ beforeAll: [],
564
+ afterAll: [],
565
+ beforeEach: [],
566
+ afterEach: []
567
+ };
568
+ }
569
+ function parseArguments(optionsOrFn, optionsOrTest) {
570
+ let options = {};
571
+ let fn = () => {};
572
+ // it('', () => {}, { retry: 2 })
573
+ if (typeof optionsOrTest === "object") {
574
+ // it('', { retry: 2 }, { retry: 3 })
575
+ if (typeof optionsOrFn === "object") {
576
+ throw new TypeError("Cannot use two objects as arguments. Please provide options and a function callback in that order.");
577
+ }
578
+ console.warn("Using an object as a third argument is deprecated. Vitest 4 will throw an error if the third argument is not a timeout number. Please use the second argument for options. See more at https://vitest.dev/guide/migration");
579
+ options = optionsOrTest;
580
+ } else if (typeof optionsOrTest === "number") {
581
+ options = { timeout: optionsOrTest };
582
+ } else if (typeof optionsOrFn === "object") {
583
+ options = optionsOrFn;
584
+ }
585
+ if (typeof optionsOrFn === "function") {
586
+ if (typeof optionsOrTest === "function") {
587
+ throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options.");
588
+ }
589
+ fn = optionsOrFn;
590
+ } else if (typeof optionsOrTest === "function") {
591
+ fn = optionsOrTest;
592
+ }
593
+ return {
594
+ options,
595
+ handler: fn
596
+ };
597
+ }
598
+ // implementations
599
+ function createSuiteCollector(name, factory = () => {}, mode, each, suiteOptions, parentCollectorFixtures) {
600
+ const tasks = [];
601
+ let suite;
602
+ initSuite(true);
603
+ const task = function(name = "", options = {}) {
604
+ var _collectorContext$cur;
605
+ const timeout = (options === null || options === void 0 ? void 0 : options.timeout) ?? runner.config.testTimeout;
606
+ const task = {
607
+ id: "",
608
+ name,
609
+ suite: (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.suite,
610
+ each: options.each,
611
+ fails: options.fails,
612
+ context: undefined,
613
+ type: "test",
614
+ file: undefined,
615
+ timeout,
616
+ retry: options.retry ?? runner.config.retry,
617
+ repeats: options.repeats,
618
+ mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run",
619
+ meta: options.meta ?? Object.create(null),
620
+ annotations: []
621
+ };
622
+ const handler = options.handler;
623
+ if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) {
624
+ task.concurrent = true;
625
+ }
626
+ task.shuffle = suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle;
627
+ const context = createTestContext(task, runner);
628
+ // create test context
629
+ Object.defineProperty(task, "context", {
630
+ value: context,
631
+ enumerable: false
632
+ });
633
+ setTestFixture(context, options.fixtures);
634
+ // custom can be called from any place, let's assume the limit is 15 stacks
635
+ const limit = Error.stackTraceLimit;
636
+ Error.stackTraceLimit = 15;
637
+ const stackTraceError = new Error("STACK_TRACE_ERROR");
638
+ Error.stackTraceLimit = limit;
639
+ if (handler) {
640
+ setFn(task, withTimeout(withAwaitAsyncAssertions(withFixtures(runner, handler, context), task), timeout, false, stackTraceError, (_, error) => abortIfTimeout([context], error)));
641
+ }
642
+ if (runner.config.includeTaskLocation) {
643
+ const error = stackTraceError.stack;
644
+ const stack = findTestFileStackTrace(error, task.each ?? false);
645
+ if (stack) {
646
+ task.location = stack;
647
+ }
648
+ }
649
+ tasks.push(task);
650
+ return task;
651
+ };
652
+ const test = createTest(function(name, optionsOrFn, optionsOrTest) {
653
+ let { options, handler } = parseArguments(optionsOrFn, optionsOrTest);
654
+ // inherit repeats, retry, timeout from suite
655
+ if (typeof suiteOptions === "object") {
656
+ options = Object.assign({}, suiteOptions, options);
657
+ }
658
+ // inherit concurrent / sequential from suite
659
+ options.concurrent = this.concurrent || !this.sequential && (options === null || options === void 0 ? void 0 : options.concurrent);
660
+ options.sequential = this.sequential || !this.concurrent && (options === null || options === void 0 ? void 0 : options.sequential);
661
+ const test = task(formatName(name), {
662
+ ...this,
663
+ ...options,
664
+ handler
665
+ });
666
+ test.type = "test";
667
+ });
668
+ let collectorFixtures = parentCollectorFixtures;
669
+ const collector = {
670
+ type: "collector",
671
+ name,
672
+ mode,
673
+ suite,
674
+ options: suiteOptions,
675
+ test,
676
+ tasks,
677
+ collect,
678
+ task,
679
+ clear,
680
+ on: addHook,
681
+ fixtures() {
682
+ return collectorFixtures;
683
+ },
684
+ scoped(fixtures) {
685
+ const parsed = mergeContextFixtures(fixtures, { fixtures: collectorFixtures }, runner);
686
+ if (parsed.fixtures) {
687
+ collectorFixtures = parsed.fixtures;
688
+ }
689
+ }
690
+ };
691
+ function addHook(name, ...fn) {
692
+ getHooks(suite)[name].push(...fn);
693
+ }
694
+ function initSuite(includeLocation) {
695
+ var _collectorContext$cur2;
696
+ if (typeof suiteOptions === "number") {
697
+ suiteOptions = { timeout: suiteOptions };
698
+ }
699
+ suite = {
700
+ id: "",
701
+ type: "suite",
702
+ name,
703
+ suite: (_collectorContext$cur2 = collectorContext.currentSuite) === null || _collectorContext$cur2 === void 0 ? void 0 : _collectorContext$cur2.suite,
704
+ mode,
705
+ each,
706
+ file: undefined,
707
+ shuffle: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle,
708
+ tasks: [],
709
+ meta: Object.create(null),
710
+ concurrent: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.concurrent
711
+ };
712
+ if (runner && includeLocation && runner.config.includeTaskLocation) {
713
+ const limit = Error.stackTraceLimit;
714
+ Error.stackTraceLimit = 15;
715
+ const error = new Error("stacktrace").stack;
716
+ Error.stackTraceLimit = limit;
717
+ const stack = findTestFileStackTrace(error, suite.each ?? false);
718
+ if (stack) {
719
+ suite.location = stack;
720
+ }
721
+ }
722
+ setHooks(suite, createSuiteHooks());
723
+ }
724
+ function clear() {
725
+ tasks.length = 0;
726
+ initSuite(false);
727
+ }
728
+ async function collect(file) {
729
+ if (!file) {
730
+ throw new TypeError("File is required to collect tasks.");
731
+ }
732
+ if (factory) {
733
+ await runWithSuite(collector, () => factory(test));
734
+ }
735
+ const allChildren = [];
736
+ for (const i of tasks) {
737
+ allChildren.push(i.type === "collector" ? await i.collect(file) : i);
738
+ }
739
+ suite.file = file;
740
+ suite.tasks = allChildren;
741
+ allChildren.forEach((task) => {
742
+ task.file = file;
743
+ });
744
+ return suite;
745
+ }
746
+ collectTask(collector);
747
+ return collector;
748
+ }
749
+ function withAwaitAsyncAssertions(fn, task) {
750
+ return async (...args) => {
751
+ const fnResult = await fn(...args);
752
+ // some async expect will be added to this array, in case user forget to await them
753
+ if (task.promises) {
754
+ const result = await Promise.allSettled(task.promises);
755
+ const errors = result.map((r) => r.status === "rejected" ? r.reason : undefined).filter(Boolean);
756
+ if (errors.length) {
757
+ throw errors;
758
+ }
759
+ }
760
+ return fnResult;
761
+ };
762
+ }
763
+ function createSuite() {
764
+ function suiteFn(name, factoryOrOptions, optionsOrFactory) {
765
+ var _currentSuite$options;
766
+ const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
767
+ const currentSuite = collectorContext.currentSuite || defaultSuite;
768
+ let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory);
769
+ const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false;
770
+ const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false;
771
+ // inherit options from current suite
772
+ options = {
773
+ ...currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.options,
774
+ ...options,
775
+ shuffle: this.shuffle ?? options.shuffle ?? (currentSuite === null || currentSuite === void 0 || (_currentSuite$options = currentSuite.options) === null || _currentSuite$options === void 0 ? void 0 : _currentSuite$options.shuffle) ?? (runner === null || runner === void 0 ? void 0 : runner.config.sequence.shuffle)
776
+ };
777
+ // inherit concurrent / sequential from suite
778
+ const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified;
779
+ const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified;
780
+ options.concurrent = isConcurrent && !isSequential;
781
+ options.sequential = isSequential && !isConcurrent;
782
+ return createSuiteCollector(formatName(name), factory, mode, this.each, options, currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fixtures());
783
+ }
784
+ suiteFn.each = function(cases, ...args) {
785
+ const suite = this.withContext();
786
+ this.setContext("each", true);
787
+ if (Array.isArray(cases) && args.length) {
788
+ cases = formatTemplateString(cases, args);
789
+ }
790
+ return (name, optionsOrFn, fnOrOptions) => {
791
+ const _name = formatName(name);
792
+ const arrayOnlyCases = cases.every(Array.isArray);
793
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
794
+ const fnFirst = typeof optionsOrFn === "function" && typeof fnOrOptions === "object";
795
+ cases.forEach((i, idx) => {
796
+ const items = Array.isArray(i) ? i : [i];
797
+ if (fnFirst) {
798
+ if (arrayOnlyCases) {
799
+ suite(formatTitle(_name, items, idx), () => handler(...items), options);
800
+ } else {
801
+ suite(formatTitle(_name, items, idx), () => handler(i), options);
802
+ }
803
+ } else {
804
+ if (arrayOnlyCases) {
805
+ suite(formatTitle(_name, items, idx), options, () => handler(...items));
806
+ } else {
807
+ suite(formatTitle(_name, items, idx), options, () => handler(i));
808
+ }
809
+ }
810
+ });
811
+ this.setContext("each", undefined);
812
+ };
813
+ };
814
+ suiteFn.for = function(cases, ...args) {
815
+ if (Array.isArray(cases) && args.length) {
816
+ cases = formatTemplateString(cases, args);
817
+ }
818
+ return (name, optionsOrFn, fnOrOptions) => {
819
+ const name_ = formatName(name);
820
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
821
+ cases.forEach((item, idx) => {
822
+ suite(formatTitle(name_, toArray(item), idx), options, () => handler(item));
823
+ });
824
+ };
825
+ };
826
+ suiteFn.skipIf = (condition) => condition ? suite.skip : suite;
827
+ suiteFn.runIf = (condition) => condition ? suite : suite.skip;
828
+ return createChainable([
829
+ "concurrent",
830
+ "sequential",
831
+ "shuffle",
832
+ "skip",
833
+ "only",
834
+ "todo"
835
+ ], suiteFn);
836
+ }
837
+ function createTaskCollector(fn, context) {
838
+ const taskFn = fn;
839
+ taskFn.each = function(cases, ...args) {
840
+ const test = this.withContext();
841
+ this.setContext("each", true);
842
+ if (Array.isArray(cases) && args.length) {
843
+ cases = formatTemplateString(cases, args);
844
+ }
845
+ return (name, optionsOrFn, fnOrOptions) => {
846
+ const _name = formatName(name);
847
+ const arrayOnlyCases = cases.every(Array.isArray);
848
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
849
+ const fnFirst = typeof optionsOrFn === "function" && typeof fnOrOptions === "object";
850
+ cases.forEach((i, idx) => {
851
+ const items = Array.isArray(i) ? i : [i];
852
+ if (fnFirst) {
853
+ if (arrayOnlyCases) {
854
+ test(formatTitle(_name, items, idx), () => handler(...items), options);
855
+ } else {
856
+ test(formatTitle(_name, items, idx), () => handler(i), options);
857
+ }
858
+ } else {
859
+ if (arrayOnlyCases) {
860
+ test(formatTitle(_name, items, idx), options, () => handler(...items));
861
+ } else {
862
+ test(formatTitle(_name, items, idx), options, () => handler(i));
863
+ }
864
+ }
865
+ });
866
+ this.setContext("each", undefined);
867
+ };
868
+ };
869
+ taskFn.for = function(cases, ...args) {
870
+ const test = this.withContext();
871
+ if (Array.isArray(cases) && args.length) {
872
+ cases = formatTemplateString(cases, args);
873
+ }
874
+ return (name, optionsOrFn, fnOrOptions) => {
875
+ const _name = formatName(name);
876
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
877
+ cases.forEach((item, idx) => {
878
+ // monkey-patch handler to allow parsing fixture
879
+ const handlerWrapper = (ctx) => handler(item, ctx);
880
+ handlerWrapper.__VITEST_FIXTURE_INDEX__ = 1;
881
+ handlerWrapper.toString = () => handler.toString();
882
+ test(formatTitle(_name, toArray(item), idx), options, handlerWrapper);
883
+ });
884
+ };
885
+ };
886
+ taskFn.skipIf = function(condition) {
887
+ return condition ? this.skip : this;
888
+ };
889
+ taskFn.runIf = function(condition) {
890
+ return condition ? this : this.skip;
891
+ };
892
+ taskFn.scoped = function(fixtures) {
893
+ const collector = getCurrentSuite();
894
+ collector.scoped(fixtures);
895
+ };
896
+ taskFn.extend = function(fixtures) {
897
+ const _context = mergeContextFixtures(fixtures, context || {}, runner);
898
+ return createTest(function fn(name, optionsOrFn, optionsOrTest) {
899
+ const collector = getCurrentSuite();
900
+ const scopedFixtures = collector.fixtures();
901
+ const context = { ...this };
902
+ if (scopedFixtures) {
903
+ context.fixtures = mergeScopedFixtures(context.fixtures || [], scopedFixtures);
904
+ }
905
+ collector.test.fn.call(context, formatName(name), optionsOrFn, optionsOrTest);
906
+ }, _context);
907
+ };
908
+ const _test = createChainable([
909
+ "concurrent",
910
+ "sequential",
911
+ "skip",
912
+ "only",
913
+ "todo",
914
+ "fails"
915
+ ], taskFn);
916
+ if (context) {
917
+ _test.mergeContext(context);
918
+ }
919
+ return _test;
920
+ }
921
+ function createTest(fn, context) {
922
+ return createTaskCollector(fn, context);
923
+ }
924
+ function formatName(name) {
925
+ return typeof name === "string" ? name : typeof name === "function" ? name.name || "<anonymous>" : String(name);
926
+ }
927
+ function formatTitle(template, items, idx) {
928
+ if (template.includes("%#") || template.includes("%$")) {
929
+ // '%#' match index of the test case
930
+ template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%");
931
+ }
932
+ const count = template.split("%").length - 1;
933
+ if (template.includes("%f")) {
934
+ const placeholders = template.match(/%f/g) || [];
935
+ placeholders.forEach((_, i) => {
936
+ if (isNegativeNaN(items[i]) || Object.is(items[i], -0)) {
937
+ // Replace the i-th occurrence of '%f' with '-%f'
938
+ let occurrence = 0;
939
+ template = template.replace(/%f/g, (match) => {
940
+ occurrence++;
941
+ return occurrence === i + 1 ? "-%f" : match;
942
+ });
943
+ }
944
+ });
945
+ }
946
+ let formatted = format(template, ...items.slice(0, count));
947
+ const isObjectItem = isObject(items[0]);
948
+ formatted = formatted.replace(/\$([$\w.]+)/g, (_, key) => {
949
+ var _runner$config;
950
+ const isArrayKey = /^\d+$/.test(key);
951
+ if (!isObjectItem && !isArrayKey) {
952
+ return `$${key}`;
953
+ }
954
+ const arrayElement = isArrayKey ? objectAttr(items, key) : undefined;
955
+ const value = isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement;
956
+ return objDisplay(value, { truncate: runner === null || runner === void 0 || (_runner$config = runner.config) === null || _runner$config === void 0 || (_runner$config = _runner$config.chaiConfig) === null || _runner$config === void 0 ? void 0 : _runner$config.truncateThreshold });
957
+ });
958
+ return formatted;
959
+ }
960
+ function formatTemplateString(cases, args) {
961
+ const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0];
962
+ const res = [];
963
+ for (let i = 0; i < Math.floor(args.length / header.length); i++) {
964
+ const oneCase = {};
965
+ for (let j = 0; j < header.length; j++) {
966
+ oneCase[header[j]] = args[i * header.length + j];
967
+ }
968
+ res.push(oneCase);
969
+ }
970
+ return res;
971
+ }
972
+ function findTestFileStackTrace(error, each) {
973
+ // first line is the error message
974
+ const lines = error.split("\n").slice(1);
975
+ for (const line of lines) {
976
+ const stack = parseSingleStack(line);
977
+ if (stack && stack.file === getTestFilepath()) {
978
+ return {
979
+ line: stack.line,
980
+ column: each ? stack.column + 1 : stack.column
981
+ };
982
+ }
983
+ }
984
+ }
985
+
986
+ /**
987
+ * If any tasks been marked as `only`, mark all other tasks as `skip`.
988
+ */
989
+ function interpretTaskModes(file, namePattern, testLocations, onlyMode, parentIsOnly, allowOnly) {
990
+ const matchedLocations = [];
991
+ const traverseSuite = (suite, parentIsOnly, parentMatchedWithLocation) => {
992
+ const suiteIsOnly = parentIsOnly || suite.mode === "only";
993
+ suite.tasks.forEach((t) => {
994
+ // Check if either the parent suite or the task itself are marked as included
995
+ const includeTask = suiteIsOnly || t.mode === "only";
996
+ if (onlyMode) {
997
+ if (t.type === "suite" && (includeTask || someTasksAreOnly(t))) {
998
+ // Don't skip this suite
999
+ if (t.mode === "only") {
1000
+ checkAllowOnly(t, allowOnly);
1001
+ t.mode = "run";
1002
+ }
1003
+ } else if (t.mode === "run" && !includeTask) {
1004
+ t.mode = "skip";
1005
+ } else if (t.mode === "only") {
1006
+ checkAllowOnly(t, allowOnly);
1007
+ t.mode = "run";
1008
+ }
1009
+ }
1010
+ let hasLocationMatch = parentMatchedWithLocation;
1011
+ // Match test location against provided locations, only run if present
1012
+ // in `testLocations`. Note: if `includeTaskLocations` is not enabled,
1013
+ // all test will be skipped.
1014
+ if (testLocations !== undefined && testLocations.length !== 0) {
1015
+ if (t.location && (testLocations === null || testLocations === void 0 ? void 0 : testLocations.includes(t.location.line))) {
1016
+ t.mode = "run";
1017
+ matchedLocations.push(t.location.line);
1018
+ hasLocationMatch = true;
1019
+ } else if (parentMatchedWithLocation) {
1020
+ t.mode = "run";
1021
+ } else if (t.type === "test") {
1022
+ t.mode = "skip";
1023
+ }
1024
+ }
1025
+ if (t.type === "test") {
1026
+ if (namePattern && !getTaskFullName(t).match(namePattern)) {
1027
+ t.mode = "skip";
1028
+ }
1029
+ } else if (t.type === "suite") {
1030
+ if (t.mode === "skip") {
1031
+ skipAllTasks(t);
1032
+ } else if (t.mode === "todo") {
1033
+ todoAllTasks(t);
1034
+ } else {
1035
+ traverseSuite(t, includeTask, hasLocationMatch);
1036
+ }
1037
+ }
1038
+ });
1039
+ // if all subtasks are skipped, mark as skip
1040
+ if (suite.mode === "run" || suite.mode === "queued") {
1041
+ if (suite.tasks.length && suite.tasks.every((i) => i.mode !== "run" && i.mode !== "queued")) {
1042
+ suite.mode = "skip";
1043
+ }
1044
+ }
1045
+ };
1046
+ traverseSuite(file, parentIsOnly, false);
1047
+ const nonMatching = testLocations === null || testLocations === void 0 ? void 0 : testLocations.filter((loc) => !matchedLocations.includes(loc));
1048
+ if (nonMatching && nonMatching.length !== 0) {
1049
+ const message = nonMatching.length === 1 ? `line ${nonMatching[0]}` : `lines ${nonMatching.join(", ")}`;
1050
+ if (file.result === undefined) {
1051
+ file.result = {
1052
+ state: "fail",
1053
+ errors: []
1054
+ };
1055
+ }
1056
+ if (file.result.errors === undefined) {
1057
+ file.result.errors = [];
1058
+ }
1059
+ file.result.errors.push(processError(new Error(`No test found in ${file.name} in ${message}`)));
1060
+ }
1061
+ }
1062
+ function getTaskFullName(task) {
1063
+ return `${task.suite ? `${getTaskFullName(task.suite)} ` : ""}${task.name}`;
1064
+ }
1065
+ function someTasksAreOnly(suite) {
1066
+ return suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t));
1067
+ }
1068
+ function skipAllTasks(suite) {
1069
+ suite.tasks.forEach((t) => {
1070
+ if (t.mode === "run" || t.mode === "queued") {
1071
+ t.mode = "skip";
1072
+ if (t.type === "suite") {
1073
+ skipAllTasks(t);
1074
+ }
1075
+ }
1076
+ });
1077
+ }
1078
+ function todoAllTasks(suite) {
1079
+ suite.tasks.forEach((t) => {
1080
+ if (t.mode === "run" || t.mode === "queued") {
1081
+ t.mode = "todo";
1082
+ if (t.type === "suite") {
1083
+ todoAllTasks(t);
1084
+ }
1085
+ }
1086
+ });
1087
+ }
1088
+ function checkAllowOnly(task, allowOnly) {
1089
+ if (allowOnly) {
1090
+ return;
1091
+ }
1092
+ const error = processError(new Error("[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error"));
1093
+ task.result = {
1094
+ state: "fail",
1095
+ errors: [error]
1096
+ };
1097
+ }
1098
+ function generateHash(str) {
1099
+ let hash = 0;
1100
+ if (str.length === 0) {
1101
+ return `${hash}`;
1102
+ }
1103
+ for (let i = 0; i < str.length; i++) {
1104
+ const char = str.charCodeAt(i);
1105
+ hash = (hash << 5) - hash + char;
1106
+ hash = hash & hash;
1107
+ }
1108
+ return `${hash}`;
1109
+ }
1110
+ function calculateSuiteHash(parent) {
1111
+ parent.tasks.forEach((t, idx) => {
1112
+ t.id = `${parent.id}_${idx}`;
1113
+ if (t.type === "suite") {
1114
+ calculateSuiteHash(t);
1115
+ }
1116
+ });
1117
+ }
1118
+ function createFileTask(filepath, root, projectName, pool) {
1119
+ const path = relative(root, filepath);
1120
+ const file = {
1121
+ id: generateFileHash(path, projectName),
1122
+ name: path,
1123
+ type: "suite",
1124
+ mode: "queued",
1125
+ filepath,
1126
+ tasks: [],
1127
+ meta: Object.create(null),
1128
+ projectName,
1129
+ file: undefined,
1130
+ pool
1131
+ };
1132
+ file.file = file;
1133
+ setFileContext(file, Object.create(null));
1134
+ return file;
1135
+ }
1136
+ /**
1137
+ * Generate a unique ID for a file based on its path and project name
1138
+ * @param file File relative to the root of the project to keep ID the same between different machines
1139
+ * @param projectName The name of the test project
1140
+ */
1141
+ function generateFileHash(file, projectName) {
1142
+ return generateHash(`${file}${projectName || ""}`);
1143
+ }
1144
+
1145
+ const now$2 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1146
+ async function collectTests(specs, runner) {
1147
+ const files = [];
1148
+ const config = runner.config;
1149
+ for (const spec of specs) {
1150
+ var _runner$onCollectStar;
1151
+ const filepath = typeof spec === "string" ? spec : spec.filepath;
1152
+ const testLocations = typeof spec === "string" ? undefined : spec.testLocations;
1153
+ const file = createFileTask(filepath, config.root, config.name, runner.pool);
1154
+ file.shuffle = config.sequence.shuffle;
1155
+ (_runner$onCollectStar = runner.onCollectStart) === null || _runner$onCollectStar === void 0 ? void 0 : _runner$onCollectStar.call(runner, file);
1156
+ clearCollectorContext(filepath, runner);
1157
+ try {
1158
+ var _runner$getImportDura;
1159
+ const setupFiles = toArray(config.setupFiles);
1160
+ if (setupFiles.length) {
1161
+ const setupStart = now$2();
1162
+ await runSetupFiles(config, setupFiles, runner);
1163
+ const setupEnd = now$2();
1164
+ file.setupDuration = setupEnd - setupStart;
1165
+ } else {
1166
+ file.setupDuration = 0;
1167
+ }
1168
+ const collectStart = now$2();
1169
+ await runner.importFile(filepath, "collect");
1170
+ const durations = (_runner$getImportDura = runner.getImportDurations) === null || _runner$getImportDura === void 0 ? void 0 : _runner$getImportDura.call(runner);
1171
+ if (durations) {
1172
+ file.importDurations = durations;
1173
+ }
1174
+ const defaultTasks = await getDefaultSuite().collect(file);
1175
+ const fileHooks = createSuiteHooks();
1176
+ mergeHooks(fileHooks, getHooks(defaultTasks));
1177
+ for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) {
1178
+ if (c.type === "test" || c.type === "suite") {
1179
+ file.tasks.push(c);
1180
+ } else if (c.type === "collector") {
1181
+ const suite = await c.collect(file);
1182
+ if (suite.name || suite.tasks.length) {
1183
+ mergeHooks(fileHooks, getHooks(suite));
1184
+ file.tasks.push(suite);
1185
+ }
1186
+ } else {
1187
+ // check that types are exhausted
1188
+ c;
1189
+ }
1190
+ }
1191
+ setHooks(file, fileHooks);
1192
+ file.collectDuration = now$2() - collectStart;
1193
+ } catch (e) {
1194
+ var _runner$getImportDura2;
1195
+ const error = processError(e);
1196
+ file.result = {
1197
+ state: "fail",
1198
+ errors: [error]
1199
+ };
1200
+ const durations = (_runner$getImportDura2 = runner.getImportDurations) === null || _runner$getImportDura2 === void 0 ? void 0 : _runner$getImportDura2.call(runner);
1201
+ if (durations) {
1202
+ file.importDurations = durations;
1203
+ }
1204
+ }
1205
+ calculateSuiteHash(file);
1206
+ const hasOnlyTasks = someTasksAreOnly(file);
1207
+ interpretTaskModes(file, config.testNamePattern, testLocations, hasOnlyTasks, false, config.allowOnly);
1208
+ if (file.mode === "queued") {
1209
+ file.mode = "run";
1210
+ }
1211
+ files.push(file);
1212
+ }
1213
+ return files;
1214
+ }
1215
+ function mergeHooks(baseHooks, hooks) {
1216
+ for (const _key in hooks) {
1217
+ const key = _key;
1218
+ baseHooks[key].push(...hooks[key]);
1219
+ }
1220
+ return baseHooks;
1221
+ }
1222
+
1223
+ /**
1224
+ * Return a function for running multiple async operations with limited concurrency.
1225
+ */
1226
+ function limitConcurrency(concurrency = Infinity) {
1227
+ // The number of currently active + pending tasks.
1228
+ let count = 0;
1229
+ // The head and tail of the pending task queue, built using a singly linked list.
1230
+ // Both head and tail are initially undefined, signifying an empty queue.
1231
+ // They both become undefined again whenever there are no pending tasks.
1232
+ let head;
1233
+ let tail;
1234
+ // A bookkeeping function executed whenever a task has been run to completion.
1235
+ const finish = () => {
1236
+ count--;
1237
+ // Check if there are further pending tasks in the queue.
1238
+ if (head) {
1239
+ // Allow the next pending task to run and pop it from the queue.
1240
+ head[0]();
1241
+ head = head[1];
1242
+ // The head may now be undefined if there are no further pending tasks.
1243
+ // In that case, set tail to undefined as well.
1244
+ tail = head && tail;
1245
+ }
1246
+ };
1247
+ return (func, ...args) => {
1248
+ // Create a promise chain that:
1249
+ // 1. Waits for its turn in the task queue (if necessary).
1250
+ // 2. Runs the task.
1251
+ // 3. Allows the next pending task (if any) to run.
1252
+ return new Promise((resolve) => {
1253
+ if (count++ < concurrency) {
1254
+ // No need to queue if fewer than maxConcurrency tasks are running.
1255
+ resolve();
1256
+ } else if (tail) {
1257
+ // There are pending tasks, so append to the queue.
1258
+ tail = tail[1] = [resolve];
1259
+ } else {
1260
+ // No other pending tasks, initialize the queue with a new tail and head.
1261
+ head = tail = [resolve];
1262
+ }
1263
+ }).then(() => {
1264
+ // Running func here ensures that even a non-thenable result or an
1265
+ // immediately thrown error gets wrapped into a Promise.
1266
+ return func(...args);
1267
+ }).finally(finish);
1268
+ };
1269
+ }
1270
+
1271
+ /**
1272
+ * Partition in tasks groups by consecutive concurrent
1273
+ */
1274
+ function partitionSuiteChildren(suite) {
1275
+ let tasksGroup = [];
1276
+ const tasksGroups = [];
1277
+ for (const c of suite.tasks) {
1278
+ if (tasksGroup.length === 0 || c.concurrent === tasksGroup[0].concurrent) {
1279
+ tasksGroup.push(c);
1280
+ } else {
1281
+ tasksGroups.push(tasksGroup);
1282
+ tasksGroup = [c];
1283
+ }
1284
+ }
1285
+ if (tasksGroup.length > 0) {
1286
+ tasksGroups.push(tasksGroup);
1287
+ }
1288
+ return tasksGroups;
1289
+ }
1290
+
1291
+ /**
1292
+ * @deprecated use `isTestCase` instead
1293
+ */
1294
+ function isAtomTest(s) {
1295
+ return isTestCase(s);
1296
+ }
1297
+ function isTestCase(s) {
1298
+ return s.type === "test";
1299
+ }
1300
+ function getTests(suite) {
1301
+ const tests = [];
1302
+ const arraySuites = toArray(suite);
1303
+ for (const s of arraySuites) {
1304
+ if (isTestCase(s)) {
1305
+ tests.push(s);
1306
+ } else {
1307
+ for (const task of s.tasks) {
1308
+ if (isTestCase(task)) {
1309
+ tests.push(task);
1310
+ } else {
1311
+ const taskTests = getTests(task);
1312
+ for (const test of taskTests) {
1313
+ tests.push(test);
1314
+ }
1315
+ }
1316
+ }
1317
+ }
1318
+ }
1319
+ return tests;
1320
+ }
1321
+ function getTasks(tasks = []) {
1322
+ return toArray(tasks).flatMap((s) => isTestCase(s) ? [s] : [s, ...getTasks(s.tasks)]);
1323
+ }
1324
+ function getSuites(suite) {
1325
+ return toArray(suite).flatMap((s) => s.type === "suite" ? [s, ...getSuites(s.tasks)] : []);
1326
+ }
1327
+ function hasTests(suite) {
1328
+ return toArray(suite).some((s) => s.tasks.some((c) => isTestCase(c) || hasTests(c)));
1329
+ }
1330
+ function hasFailed(suite) {
1331
+ return toArray(suite).some((s) => {
1332
+ var _s$result;
1333
+ return ((_s$result = s.result) === null || _s$result === void 0 ? void 0 : _s$result.state) === "fail" || s.type === "suite" && hasFailed(s.tasks);
1334
+ });
1335
+ }
1336
+ function getNames(task) {
1337
+ const names = [task.name];
1338
+ let current = task;
1339
+ while (current === null || current === void 0 ? void 0 : current.suite) {
1340
+ current = current.suite;
1341
+ if (current === null || current === void 0 ? void 0 : current.name) {
1342
+ names.unshift(current.name);
1343
+ }
1344
+ }
1345
+ if (current !== task.file) {
1346
+ names.unshift(task.file.name);
1347
+ }
1348
+ return names;
1349
+ }
1350
+ function getFullName(task, separator = " > ") {
1351
+ return getNames(task).join(separator);
1352
+ }
1353
+ function getTestName(task, separator = " > ") {
1354
+ return getNames(task).slice(1).join(separator);
1355
+ }
1356
+
1357
+ const now$1 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1358
+ const unixNow = Date.now;
1359
+ function updateSuiteHookState(task, name, state, runner) {
1360
+ if (!task.result) {
1361
+ task.result = { state: "run" };
1362
+ }
1363
+ if (!task.result.hooks) {
1364
+ task.result.hooks = {};
1365
+ }
1366
+ const suiteHooks = task.result.hooks;
1367
+ if (suiteHooks) {
1368
+ suiteHooks[name] = state;
1369
+ let event = state === "run" ? "before-hook-start" : "before-hook-end";
1370
+ if (name === "afterAll" || name === "afterEach") {
1371
+ event = state === "run" ? "after-hook-start" : "after-hook-end";
1372
+ }
1373
+ updateTask(event, task, runner);
1374
+ }
1375
+ }
1376
+ function getSuiteHooks(suite, name, sequence) {
1377
+ const hooks = getHooks(suite)[name];
1378
+ if (sequence === "stack" && (name === "afterAll" || name === "afterEach")) {
1379
+ return hooks.slice().reverse();
1380
+ }
1381
+ return hooks;
1382
+ }
1383
+ async function callTestHooks(runner, test, hooks, sequence) {
1384
+ if (sequence === "stack") {
1385
+ hooks = hooks.slice().reverse();
1386
+ }
1387
+ if (!hooks.length) {
1388
+ return;
1389
+ }
1390
+ const context = test.context;
1391
+ const onTestFailed = test.context.onTestFailed;
1392
+ const onTestFinished = test.context.onTestFinished;
1393
+ context.onTestFailed = () => {
1394
+ throw new Error(`Cannot call "onTestFailed" inside a test hook.`);
1395
+ };
1396
+ context.onTestFinished = () => {
1397
+ throw new Error(`Cannot call "onTestFinished" inside a test hook.`);
1398
+ };
1399
+ if (sequence === "parallel") {
1400
+ try {
1401
+ await Promise.all(hooks.map((fn) => fn(test.context)));
1402
+ } catch (e) {
1403
+ failTask(test.result, e, runner.config.diffOptions);
1404
+ }
1405
+ } else {
1406
+ for (const fn of hooks) {
1407
+ try {
1408
+ await fn(test.context);
1409
+ } catch (e) {
1410
+ failTask(test.result, e, runner.config.diffOptions);
1411
+ }
1412
+ }
1413
+ }
1414
+ context.onTestFailed = onTestFailed;
1415
+ context.onTestFinished = onTestFinished;
1416
+ }
1417
+ async function callSuiteHook(suite, currentTask, name, runner, args) {
1418
+ const sequence = runner.config.sequence.hooks;
1419
+ const callbacks = [];
1420
+ // stop at file level
1421
+ const parentSuite = "filepath" in suite ? null : suite.suite || suite.file;
1422
+ if (name === "beforeEach" && parentSuite) {
1423
+ callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args));
1424
+ }
1425
+ const hooks = getSuiteHooks(suite, name, sequence);
1426
+ if (hooks.length > 0) {
1427
+ updateSuiteHookState(currentTask, name, "run", runner);
1428
+ }
1429
+ async function runHook(hook) {
1430
+ return getBeforeHookCleanupCallback(hook, await hook(...args), name === "beforeEach" ? args[0] : undefined);
1431
+ }
1432
+ if (sequence === "parallel") {
1433
+ callbacks.push(...await Promise.all(hooks.map((hook) => runHook(hook))));
1434
+ } else {
1435
+ for (const hook of hooks) {
1436
+ callbacks.push(await runHook(hook));
1437
+ }
1438
+ }
1439
+ if (hooks.length > 0) {
1440
+ updateSuiteHookState(currentTask, name, "pass", runner);
1441
+ }
1442
+ if (name === "afterEach" && parentSuite) {
1443
+ callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args));
1444
+ }
1445
+ return callbacks;
1446
+ }
1447
+ const packs = new Map();
1448
+ const eventsPacks = [];
1449
+ const pendingTasksUpdates = [];
1450
+ function sendTasksUpdate(runner) {
1451
+ if (packs.size) {
1452
+ var _runner$onTaskUpdate;
1453
+ const taskPacks = Array.from(packs).map(([id, task]) => {
1454
+ return [
1455
+ id,
1456
+ task[0],
1457
+ task[1]
1458
+ ];
1459
+ });
1460
+ const p = (_runner$onTaskUpdate = runner.onTaskUpdate) === null || _runner$onTaskUpdate === void 0 ? void 0 : _runner$onTaskUpdate.call(runner, taskPacks, eventsPacks);
1461
+ if (p) {
1462
+ pendingTasksUpdates.push(p);
1463
+ // remove successful promise to not grow array indefnitely,
1464
+ // but keep rejections so finishSendTasksUpdate can handle them
1465
+ p.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p), 1), () => {});
1466
+ }
1467
+ eventsPacks.length = 0;
1468
+ packs.clear();
1469
+ }
1470
+ }
1471
+ async function finishSendTasksUpdate(runner) {
1472
+ sendTasksUpdate(runner);
1473
+ await Promise.all(pendingTasksUpdates);
1474
+ }
1475
+ function throttle(fn, ms) {
1476
+ let last = 0;
1477
+ return function(...args) {
1478
+ const now = unixNow();
1479
+ if (now - last > ms) {
1480
+ last = now;
1481
+ return fn.apply(this, args);
1482
+ }
1483
+ };
1484
+ }
1485
+ // throttle based on summary reporter's DURATION_UPDATE_INTERVAL_MS
1486
+ const sendTasksUpdateThrottled = throttle(sendTasksUpdate, 100);
1487
+ function updateTask(event, task, runner) {
1488
+ eventsPacks.push([
1489
+ task.id,
1490
+ event,
1491
+ undefined
1492
+ ]);
1493
+ packs.set(task.id, [task.result, task.meta]);
1494
+ sendTasksUpdateThrottled(runner);
1495
+ }
1496
+ async function callCleanupHooks(runner, cleanups) {
1497
+ const sequence = runner.config.sequence.hooks;
1498
+ if (sequence === "stack") {
1499
+ cleanups = cleanups.slice().reverse();
1500
+ }
1501
+ if (sequence === "parallel") {
1502
+ await Promise.all(cleanups.map(async (fn) => {
1503
+ if (typeof fn !== "function") {
1504
+ return;
1505
+ }
1506
+ await fn();
1507
+ }));
1508
+ } else {
1509
+ for (const fn of cleanups) {
1510
+ if (typeof fn !== "function") {
1511
+ continue;
1512
+ }
1513
+ await fn();
1514
+ }
1515
+ }
1516
+ }
1517
+ async function runTest(test, runner) {
1518
+ var _runner$onBeforeRunTa, _test$result, _runner$onAfterRunTas;
1519
+ await ((_runner$onBeforeRunTa = runner.onBeforeRunTask) === null || _runner$onBeforeRunTa === void 0 ? void 0 : _runner$onBeforeRunTa.call(runner, test));
1520
+ if (test.mode !== "run" && test.mode !== "queued") {
1521
+ updateTask("test-prepare", test, runner);
1522
+ updateTask("test-finished", test, runner);
1523
+ return;
1524
+ }
1525
+ if (((_test$result = test.result) === null || _test$result === void 0 ? void 0 : _test$result.state) === "fail") {
1526
+ // should not be possible to get here, I think this is just copy pasted from suite
1527
+ // TODO: maybe someone fails tests in `beforeAll` hooks?
1528
+ // https://github.com/vitest-dev/vitest/pull/7069
1529
+ updateTask("test-failed-early", test, runner);
1530
+ return;
1531
+ }
1532
+ const start = now$1();
1533
+ test.result = {
1534
+ state: "run",
1535
+ startTime: unixNow(),
1536
+ retryCount: 0
1537
+ };
1538
+ updateTask("test-prepare", test, runner);
1539
+ const cleanupRunningTest = addRunningTest(test);
1540
+ setCurrentTest(test);
1541
+ const suite = test.suite || test.file;
1542
+ const repeats = test.repeats ?? 0;
1543
+ for (let repeatCount = 0; repeatCount <= repeats; repeatCount++) {
1544
+ const retry = test.retry ?? 0;
1545
+ for (let retryCount = 0; retryCount <= retry; retryCount++) {
1546
+ var _test$result2, _test$result3;
1547
+ let beforeEachCleanups = [];
1548
+ try {
1549
+ var _runner$onBeforeTryTa, _runner$onAfterTryTas;
1550
+ await ((_runner$onBeforeTryTa = runner.onBeforeTryTask) === null || _runner$onBeforeTryTa === void 0 ? void 0 : _runner$onBeforeTryTa.call(runner, test, {
1551
+ retry: retryCount,
1552
+ repeats: repeatCount
1553
+ }));
1554
+ test.result.repeatCount = repeatCount;
1555
+ beforeEachCleanups = await callSuiteHook(suite, test, "beforeEach", runner, [test.context, suite]);
1556
+ if (runner.runTask) {
1557
+ await runner.runTask(test);
1558
+ } else {
1559
+ const fn = getFn(test);
1560
+ if (!fn) {
1561
+ throw new Error("Test function is not found. Did you add it using `setFn`?");
1562
+ }
1563
+ await fn();
1564
+ }
1565
+ await ((_runner$onAfterTryTas = runner.onAfterTryTask) === null || _runner$onAfterTryTas === void 0 ? void 0 : _runner$onAfterTryTas.call(runner, test, {
1566
+ retry: retryCount,
1567
+ repeats: repeatCount
1568
+ }));
1569
+ if (test.result.state !== "fail") {
1570
+ if (!test.repeats) {
1571
+ test.result.state = "pass";
1572
+ } else if (test.repeats && retry === retryCount) {
1573
+ test.result.state = "pass";
1574
+ }
1575
+ }
1576
+ } catch (e) {
1577
+ failTask(test.result, e, runner.config.diffOptions);
1578
+ }
1579
+ try {
1580
+ var _runner$onTaskFinishe;
1581
+ await ((_runner$onTaskFinishe = runner.onTaskFinished) === null || _runner$onTaskFinishe === void 0 ? void 0 : _runner$onTaskFinishe.call(runner, test));
1582
+ } catch (e) {
1583
+ failTask(test.result, e, runner.config.diffOptions);
1584
+ }
1585
+ try {
1586
+ await callSuiteHook(suite, test, "afterEach", runner, [test.context, suite]);
1587
+ await callCleanupHooks(runner, beforeEachCleanups);
1588
+ await callFixtureCleanup(test.context);
1589
+ } catch (e) {
1590
+ failTask(test.result, e, runner.config.diffOptions);
1591
+ }
1592
+ await callTestHooks(runner, test, test.onFinished || [], "stack");
1593
+ if (test.result.state === "fail") {
1594
+ await callTestHooks(runner, test, test.onFailed || [], runner.config.sequence.hooks);
1595
+ }
1596
+ test.onFailed = undefined;
1597
+ test.onFinished = undefined;
1598
+ // skipped with new PendingError
1599
+ if (((_test$result2 = test.result) === null || _test$result2 === void 0 ? void 0 : _test$result2.pending) || ((_test$result3 = test.result) === null || _test$result3 === void 0 ? void 0 : _test$result3.state) === "skip") {
1600
+ var _test$result4;
1601
+ test.mode = "skip";
1602
+ test.result = {
1603
+ state: "skip",
1604
+ note: (_test$result4 = test.result) === null || _test$result4 === void 0 ? void 0 : _test$result4.note,
1605
+ pending: true,
1606
+ duration: now$1() - start
1607
+ };
1608
+ updateTask("test-finished", test, runner);
1609
+ setCurrentTest(undefined);
1610
+ cleanupRunningTest();
1611
+ return;
1612
+ }
1613
+ if (test.result.state === "pass") {
1614
+ break;
1615
+ }
1616
+ if (retryCount < retry) {
1617
+ // reset state when retry test
1618
+ test.result.state = "run";
1619
+ test.result.retryCount = (test.result.retryCount ?? 0) + 1;
1620
+ }
1621
+ // update retry info
1622
+ updateTask("test-retried", test, runner);
1623
+ }
1624
+ }
1625
+ // if test is marked to be failed, flip the result
1626
+ if (test.fails) {
1627
+ if (test.result.state === "pass") {
1628
+ const error = processError(new Error("Expect test to fail"));
1629
+ test.result.state = "fail";
1630
+ test.result.errors = [error];
1631
+ } else {
1632
+ test.result.state = "pass";
1633
+ test.result.errors = undefined;
1634
+ }
1635
+ }
1636
+ cleanupRunningTest();
1637
+ setCurrentTest(undefined);
1638
+ test.result.duration = now$1() - start;
1639
+ await ((_runner$onAfterRunTas = runner.onAfterRunTask) === null || _runner$onAfterRunTas === void 0 ? void 0 : _runner$onAfterRunTas.call(runner, test));
1640
+ updateTask("test-finished", test, runner);
1641
+ }
1642
+ function failTask(result, err, diffOptions) {
1643
+ if (err instanceof PendingError) {
1644
+ result.state = "skip";
1645
+ result.note = err.note;
1646
+ result.pending = true;
1647
+ return;
1648
+ }
1649
+ result.state = "fail";
1650
+ const errors = Array.isArray(err) ? err : [err];
1651
+ for (const e of errors) {
1652
+ const error = processError(e, diffOptions);
1653
+ result.errors ?? (result.errors = []);
1654
+ result.errors.push(error);
1655
+ }
1656
+ }
1657
+ function markTasksAsSkipped(suite, runner) {
1658
+ suite.tasks.forEach((t) => {
1659
+ t.mode = "skip";
1660
+ t.result = {
1661
+ ...t.result,
1662
+ state: "skip"
1663
+ };
1664
+ updateTask("test-finished", t, runner);
1665
+ if (t.type === "suite") {
1666
+ markTasksAsSkipped(t, runner);
1667
+ }
1668
+ });
1669
+ }
1670
+ async function runSuite(suite, runner) {
1671
+ var _runner$onBeforeRunSu, _suite$result;
1672
+ await ((_runner$onBeforeRunSu = runner.onBeforeRunSuite) === null || _runner$onBeforeRunSu === void 0 ? void 0 : _runner$onBeforeRunSu.call(runner, suite));
1673
+ if (((_suite$result = suite.result) === null || _suite$result === void 0 ? void 0 : _suite$result.state) === "fail") {
1674
+ markTasksAsSkipped(suite, runner);
1675
+ // failed during collection
1676
+ updateTask("suite-failed-early", suite, runner);
1677
+ return;
1678
+ }
1679
+ const start = now$1();
1680
+ const mode = suite.mode;
1681
+ suite.result = {
1682
+ state: mode === "skip" || mode === "todo" ? mode : "run",
1683
+ startTime: unixNow()
1684
+ };
1685
+ updateTask("suite-prepare", suite, runner);
1686
+ let beforeAllCleanups = [];
1687
+ if (suite.mode === "skip") {
1688
+ suite.result.state = "skip";
1689
+ updateTask("suite-finished", suite, runner);
1690
+ } else if (suite.mode === "todo") {
1691
+ suite.result.state = "todo";
1692
+ updateTask("suite-finished", suite, runner);
1693
+ } else {
1694
+ var _runner$onAfterRunSui;
1695
+ try {
1696
+ try {
1697
+ beforeAllCleanups = await callSuiteHook(suite, suite, "beforeAll", runner, [suite]);
1698
+ } catch (e) {
1699
+ markTasksAsSkipped(suite, runner);
1700
+ throw e;
1701
+ }
1702
+ if (runner.runSuite) {
1703
+ await runner.runSuite(suite);
1704
+ } else {
1705
+ for (let tasksGroup of partitionSuiteChildren(suite)) {
1706
+ if (tasksGroup[0].concurrent === true) {
1707
+ await Promise.all(tasksGroup.map((c) => runSuiteChild(c, runner)));
1708
+ } else {
1709
+ const { sequence } = runner.config;
1710
+ if (suite.shuffle) {
1711
+ // run describe block independently from tests
1712
+ const suites = tasksGroup.filter((group) => group.type === "suite");
1713
+ const tests = tasksGroup.filter((group) => group.type === "test");
1714
+ const groups = shuffle([suites, tests], sequence.seed);
1715
+ tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed));
1716
+ }
1717
+ for (const c of tasksGroup) {
1718
+ await runSuiteChild(c, runner);
1719
+ }
1720
+ }
1721
+ }
1722
+ }
1723
+ } catch (e) {
1724
+ failTask(suite.result, e, runner.config.diffOptions);
1725
+ }
1726
+ try {
1727
+ await callSuiteHook(suite, suite, "afterAll", runner, [suite]);
1728
+ await callCleanupHooks(runner, beforeAllCleanups);
1729
+ if (suite.file === suite) {
1730
+ const context = getFileContext(suite);
1731
+ await callFixtureCleanup(context);
1732
+ }
1733
+ } catch (e) {
1734
+ failTask(suite.result, e, runner.config.diffOptions);
1735
+ }
1736
+ if (suite.mode === "run" || suite.mode === "queued") {
1737
+ if (!runner.config.passWithNoTests && !hasTests(suite)) {
1738
+ var _suite$result$errors;
1739
+ suite.result.state = "fail";
1740
+ if (!((_suite$result$errors = suite.result.errors) === null || _suite$result$errors === void 0 ? void 0 : _suite$result$errors.length)) {
1741
+ const error = processError(new Error(`No test found in suite ${suite.name}`));
1742
+ suite.result.errors = [error];
1743
+ }
1744
+ } else if (hasFailed(suite)) {
1745
+ suite.result.state = "fail";
1746
+ } else {
1747
+ suite.result.state = "pass";
1748
+ }
1749
+ }
1750
+ suite.result.duration = now$1() - start;
1751
+ updateTask("suite-finished", suite, runner);
1752
+ await ((_runner$onAfterRunSui = runner.onAfterRunSuite) === null || _runner$onAfterRunSui === void 0 ? void 0 : _runner$onAfterRunSui.call(runner, suite));
1753
+ }
1754
+ }
1755
+ let limitMaxConcurrency;
1756
+ async function runSuiteChild(c, runner) {
1757
+ if (c.type === "test") {
1758
+ return limitMaxConcurrency(() => runTest(c, runner));
1759
+ } else if (c.type === "suite") {
1760
+ return runSuite(c, runner);
1761
+ }
1762
+ }
1763
+ async function runFiles(files, runner) {
1764
+ limitMaxConcurrency ?? (limitMaxConcurrency = limitConcurrency(runner.config.maxConcurrency));
1765
+ for (const file of files) {
1766
+ if (!file.tasks.length && !runner.config.passWithNoTests) {
1767
+ var _file$result;
1768
+ if (!((_file$result = file.result) === null || _file$result === void 0 || (_file$result = _file$result.errors) === null || _file$result === void 0 ? void 0 : _file$result.length)) {
1769
+ const error = processError(new Error(`No test suite found in file ${file.filepath}`));
1770
+ file.result = {
1771
+ state: "fail",
1772
+ errors: [error]
1773
+ };
1774
+ }
1775
+ }
1776
+ await runSuite(file, runner);
1777
+ }
1778
+ }
1779
+ const workerRunners = new WeakSet();
1780
+ async function startTests(specs, runner) {
1781
+ var _runner$cancel;
1782
+ const cancel = (_runner$cancel = runner.cancel) === null || _runner$cancel === void 0 ? void 0 : _runner$cancel.bind(runner);
1783
+ // Ideally, we need to have an event listener for this, but only have a runner here.
1784
+ // Adding another onCancel felt wrong (maybe it needs to be refactored)
1785
+ runner.cancel = (reason) => {
1786
+ // We intentionally create only one error since there is only one test run that can be cancelled
1787
+ const error = new TestRunAbortError("The test run was aborted by the user.", reason);
1788
+ getRunningTests().forEach((test) => abortContextSignal(test.context, error));
1789
+ return cancel === null || cancel === void 0 ? void 0 : cancel(reason);
1790
+ };
1791
+ if (!workerRunners.has(runner)) {
1792
+ var _runner$onCleanupWork;
1793
+ (_runner$onCleanupWork = runner.onCleanupWorkerContext) === null || _runner$onCleanupWork === void 0 ? void 0 : _runner$onCleanupWork.call(runner, async () => {
1794
+ var _runner$getWorkerCont;
1795
+ const context = (_runner$getWorkerCont = runner.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner);
1796
+ if (context) {
1797
+ await callFixtureCleanup(context);
1798
+ }
1799
+ });
1800
+ workerRunners.add(runner);
1801
+ }
1802
+ try {
1803
+ var _runner$onBeforeColle, _runner$onCollected, _runner$onBeforeRunFi, _runner$onAfterRunFil;
1804
+ const paths = specs.map((f) => typeof f === "string" ? f : f.filepath);
1805
+ await ((_runner$onBeforeColle = runner.onBeforeCollect) === null || _runner$onBeforeColle === void 0 ? void 0 : _runner$onBeforeColle.call(runner, paths));
1806
+ const files = await collectTests(specs, runner);
1807
+ await ((_runner$onCollected = runner.onCollected) === null || _runner$onCollected === void 0 ? void 0 : _runner$onCollected.call(runner, files));
1808
+ await ((_runner$onBeforeRunFi = runner.onBeforeRunFiles) === null || _runner$onBeforeRunFi === void 0 ? void 0 : _runner$onBeforeRunFi.call(runner, files));
1809
+ await runFiles(files, runner);
1810
+ await ((_runner$onAfterRunFil = runner.onAfterRunFiles) === null || _runner$onAfterRunFil === void 0 ? void 0 : _runner$onAfterRunFil.call(runner, files));
1811
+ await finishSendTasksUpdate(runner);
1812
+ return files;
1813
+ } finally {
1814
+ runner.cancel = cancel;
1815
+ }
1816
+ }
1817
+ async function publicCollect(specs, runner) {
1818
+ var _runner$onBeforeColle2, _runner$onCollected2;
1819
+ const paths = specs.map((f) => typeof f === "string" ? f : f.filepath);
1820
+ await ((_runner$onBeforeColle2 = runner.onBeforeCollect) === null || _runner$onBeforeColle2 === void 0 ? void 0 : _runner$onBeforeColle2.call(runner, paths));
1821
+ const files = await collectTests(specs, runner);
1822
+ await ((_runner$onCollected2 = runner.onCollected) === null || _runner$onCollected2 === void 0 ? void 0 : _runner$onCollected2.call(runner, files));
1823
+ return files;
1824
+ }
1825
+
1826
+ const now = Date.now;
1827
+ const collectorContext = {
1828
+ tasks: [],
1829
+ currentSuite: null
1830
+ };
1831
+ function collectTask(task) {
1832
+ var _collectorContext$cur;
1833
+ (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.tasks.push(task);
1834
+ }
1835
+ async function runWithSuite(suite, fn) {
1836
+ const prev = collectorContext.currentSuite;
1837
+ collectorContext.currentSuite = suite;
1838
+ await fn();
1839
+ collectorContext.currentSuite = prev;
1840
+ }
1841
+ function withTimeout(fn, timeout, isHook = false, stackTraceError, onTimeout) {
1842
+ if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) {
1843
+ return fn;
1844
+ }
1845
+ const { setTimeout, clearTimeout } = getSafeTimers();
1846
+ // this function name is used to filter error in test/cli/test/fails.test.ts
1847
+ return function runWithTimeout(...args) {
1848
+ const startTime = now();
1849
+ const runner = getRunner();
1850
+ runner._currentTaskStartTime = startTime;
1851
+ runner._currentTaskTimeout = timeout;
1852
+ return new Promise((resolve_, reject_) => {
1853
+ var _timer$unref;
1854
+ const timer = setTimeout(() => {
1855
+ clearTimeout(timer);
1856
+ rejectTimeoutError();
1857
+ }, timeout);
1858
+ // `unref` might not exist in browser
1859
+ (_timer$unref = timer.unref) === null || _timer$unref === void 0 ? void 0 : _timer$unref.call(timer);
1860
+ function rejectTimeoutError() {
1861
+ const error = makeTimeoutError(isHook, timeout, stackTraceError);
1862
+ onTimeout === null || onTimeout === void 0 ? void 0 : onTimeout(args, error);
1863
+ reject_(error);
1864
+ }
1865
+ function resolve(result) {
1866
+ runner._currentTaskStartTime = undefined;
1867
+ runner._currentTaskTimeout = undefined;
1868
+ clearTimeout(timer);
1869
+ // if test/hook took too long in microtask, setTimeout won't be triggered,
1870
+ // but we still need to fail the test, see
1871
+ // https://github.com/vitest-dev/vitest/issues/2920
1872
+ if (now() - startTime >= timeout) {
1873
+ rejectTimeoutError();
1874
+ return;
1875
+ }
1876
+ resolve_(result);
1877
+ }
1878
+ function reject(error) {
1879
+ runner._currentTaskStartTime = undefined;
1880
+ runner._currentTaskTimeout = undefined;
1881
+ clearTimeout(timer);
1882
+ reject_(error);
1883
+ }
1884
+ // sync test/hook will be caught by try/catch
1885
+ try {
1886
+ const result = fn(...args);
1887
+ // the result is a thenable, we don't wrap this in Promise.resolve
1888
+ // to avoid creating new promises
1889
+ if (typeof result === "object" && result != null && typeof result.then === "function") {
1890
+ result.then(resolve, reject);
1891
+ } else {
1892
+ resolve(result);
1893
+ }
1894
+ }
1895
+ // user sync test/hook throws an error
1896
+ catch (error) {
1897
+ reject(error);
1898
+ }
1899
+ });
1900
+ };
1901
+ }
1902
+ const abortControllers = new WeakMap();
1903
+ function abortIfTimeout([context], error) {
1904
+ if (context) {
1905
+ abortContextSignal(context, error);
1906
+ }
1907
+ }
1908
+ function abortContextSignal(context, error) {
1909
+ const abortController = abortControllers.get(context);
1910
+ abortController === null || abortController === void 0 ? void 0 : abortController.abort(error);
1911
+ }
1912
+ function createTestContext(test, runner) {
1913
+ var _runner$extendTaskCon;
1914
+ const context = function() {
1915
+ throw new Error("done() callback is deprecated, use promise instead");
1916
+ };
1917
+ let abortController = abortControllers.get(context);
1918
+ if (!abortController) {
1919
+ abortController = new AbortController();
1920
+ abortControllers.set(context, abortController);
1921
+ }
1922
+ context.signal = abortController.signal;
1923
+ context.task = test;
1924
+ context.skip = (condition, note) => {
1925
+ if (condition === false) {
1926
+ // do nothing
1927
+ return undefined;
1928
+ }
1929
+ test.result ?? (test.result = { state: "skip" });
1930
+ test.result.pending = true;
1931
+ throw new PendingError("test is skipped; abort execution", test, typeof condition === "string" ? condition : note);
1932
+ };
1933
+ async function annotate(message, location, type, attachment) {
1934
+ const annotation = {
1935
+ message,
1936
+ type: type || "notice"
1937
+ };
1938
+ if (attachment) {
1939
+ if (!attachment.body && !attachment.path) {
1940
+ throw new TypeError(`Test attachment requires body or path to be set. Both are missing.`);
1941
+ }
1942
+ if (attachment.body && attachment.path) {
1943
+ throw new TypeError(`Test attachment requires only one of "body" or "path" to be set. Both are specified.`);
1944
+ }
1945
+ annotation.attachment = attachment;
1946
+ // convert to a string so it's easier to serialise
1947
+ if (attachment.body instanceof Uint8Array) {
1948
+ attachment.body = encodeUint8Array(attachment.body);
1949
+ }
1950
+ }
1951
+ if (location) {
1952
+ annotation.location = location;
1953
+ }
1954
+ if (!runner.onTestAnnotate) {
1955
+ throw new Error(`Test runner doesn't support test annotations.`);
1956
+ }
1957
+ await finishSendTasksUpdate(runner);
1958
+ const resolvedAnnotation = await runner.onTestAnnotate(test, annotation);
1959
+ test.annotations.push(resolvedAnnotation);
1960
+ return resolvedAnnotation;
1961
+ }
1962
+ context.annotate = (message, type, attachment) => {
1963
+ if (test.result && test.result.state !== "run") {
1964
+ throw new Error(`Cannot annotate tests outside of the test run. The test "${test.name}" finished running with the "${test.result.state}" state already.`);
1965
+ }
1966
+ let location;
1967
+ const stack = new Error("STACK_TRACE").stack;
1968
+ const index = stack.includes("STACK_TRACE") ? 2 : 1;
1969
+ const stackLine = stack.split("\n")[index];
1970
+ const parsed = parseSingleStack(stackLine);
1971
+ if (parsed) {
1972
+ location = {
1973
+ file: parsed.file,
1974
+ line: parsed.line,
1975
+ column: parsed.column
1976
+ };
1977
+ }
1978
+ if (typeof type === "object") {
1979
+ return recordAsyncAnnotation(test, annotate(message, location, undefined, type));
1980
+ } else {
1981
+ return recordAsyncAnnotation(test, annotate(message, location, type, attachment));
1982
+ }
1983
+ };
1984
+ context.onTestFailed = (handler, timeout) => {
1985
+ test.onFailed || (test.onFailed = []);
1986
+ test.onFailed.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
1987
+ };
1988
+ context.onTestFinished = (handler, timeout) => {
1989
+ test.onFinished || (test.onFinished = []);
1990
+ test.onFinished.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
1991
+ };
1992
+ return ((_runner$extendTaskCon = runner.extendTaskContext) === null || _runner$extendTaskCon === void 0 ? void 0 : _runner$extendTaskCon.call(runner, context)) || context;
1993
+ }
1994
+ function makeTimeoutError(isHook, timeout, stackTraceError) {
1995
+ const message = `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.\nIf this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`;
1996
+ const error = new Error(message);
1997
+ if (stackTraceError === null || stackTraceError === void 0 ? void 0 : stackTraceError.stack) {
1998
+ error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message);
1999
+ }
2000
+ return error;
2001
+ }
2002
+ const fileContexts = new WeakMap();
2003
+ function getFileContext(file) {
2004
+ const context = fileContexts.get(file);
2005
+ if (!context) {
2006
+ throw new Error(`Cannot find file context for ${file.name}`);
2007
+ }
2008
+ return context;
2009
+ }
2010
+ function setFileContext(file, context) {
2011
+ fileContexts.set(file, context);
2012
+ }
2013
+ const table = [];
2014
+ for (let i = 65; i < 91; i++) {
2015
+ table.push(String.fromCharCode(i));
2016
+ }
2017
+ for (let i = 97; i < 123; i++) {
2018
+ table.push(String.fromCharCode(i));
2019
+ }
2020
+ for (let i = 0; i < 10; i++) {
2021
+ table.push(i.toString(10));
2022
+ }
2023
+ function encodeUint8Array(bytes) {
2024
+ let base64 = "";
2025
+ const len = bytes.byteLength;
2026
+ for (let i = 0; i < len; i += 3) {
2027
+ if (len === i + 1) {
2028
+ const a = (bytes[i] & 252) >> 2;
2029
+ const b = (bytes[i] & 3) << 4;
2030
+ base64 += table[a];
2031
+ base64 += table[b];
2032
+ base64 += "==";
2033
+ } else if (len === i + 2) {
2034
+ const a = (bytes[i] & 252) >> 2;
2035
+ const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
2036
+ const c = (bytes[i + 1] & 15) << 2;
2037
+ base64 += table[a];
2038
+ base64 += table[b];
2039
+ base64 += table[c];
2040
+ base64 += "=";
2041
+ } else {
2042
+ const a = (bytes[i] & 252) >> 2;
2043
+ const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
2044
+ const c = (bytes[i + 1] & 15) << 2 | (bytes[i + 2] & 192) >> 6;
2045
+ const d = bytes[i + 2] & 63;
2046
+ base64 += table[a];
2047
+ base64 += table[b];
2048
+ base64 += table[c];
2049
+ base64 += table[d];
2050
+ }
2051
+ }
2052
+ return base64;
2053
+ }
2054
+ function recordAsyncAnnotation(test, promise) {
2055
+ // if promise is explicitly awaited, remove it from the list
2056
+ promise = promise.finally(() => {
2057
+ if (!test.promises) {
2058
+ return;
2059
+ }
2060
+ const index = test.promises.indexOf(promise);
2061
+ if (index !== -1) {
2062
+ test.promises.splice(index, 1);
2063
+ }
2064
+ });
2065
+ // record promise
2066
+ if (!test.promises) {
2067
+ test.promises = [];
2068
+ }
2069
+ test.promises.push(promise);
2070
+ return promise;
2071
+ }
2072
+
2073
+ function getDefaultHookTimeout() {
2074
+ return getRunner().config.hookTimeout;
2075
+ }
2076
+ const CLEANUP_TIMEOUT_KEY = Symbol.for("VITEST_CLEANUP_TIMEOUT");
2077
+ const CLEANUP_STACK_TRACE_KEY = Symbol.for("VITEST_CLEANUP_STACK_TRACE");
2078
+ function getBeforeHookCleanupCallback(hook, result, context) {
2079
+ if (typeof result === "function") {
2080
+ const timeout = CLEANUP_TIMEOUT_KEY in hook && typeof hook[CLEANUP_TIMEOUT_KEY] === "number" ? hook[CLEANUP_TIMEOUT_KEY] : getDefaultHookTimeout();
2081
+ const stackTraceError = CLEANUP_STACK_TRACE_KEY in hook && hook[CLEANUP_STACK_TRACE_KEY] instanceof Error ? hook[CLEANUP_STACK_TRACE_KEY] : undefined;
2082
+ return withTimeout(result, timeout, true, stackTraceError, (_, error) => {
2083
+ if (context) {
2084
+ abortContextSignal(context, error);
2085
+ }
2086
+ });
2087
+ }
2088
+ }
2089
+ /**
2090
+ * Registers a callback function to be executed once before all tests within the current suite.
2091
+ * This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment.
2092
+ *
2093
+ * **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
2094
+ *
2095
+ * @param {Function} fn - The callback function to be executed before all tests.
2096
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2097
+ * @returns {void}
2098
+ * @example
2099
+ * ```ts
2100
+ * // Example of using beforeAll to set up a database connection
2101
+ * beforeAll(async () => {
2102
+ * await database.connect();
2103
+ * });
2104
+ * ```
2105
+ */
2106
+ function beforeAll(fn, timeout = getDefaultHookTimeout()) {
2107
+ assertTypes(fn, "\"beforeAll\" callback", ["function"]);
2108
+ const stackTraceError = new Error("STACK_TRACE_ERROR");
2109
+ return getCurrentSuite().on("beforeAll", Object.assign(withTimeout(fn, timeout, true, stackTraceError), {
2110
+ [CLEANUP_TIMEOUT_KEY]: timeout,
2111
+ [CLEANUP_STACK_TRACE_KEY]: stackTraceError
2112
+ }));
2113
+ }
2114
+ /**
2115
+ * Registers a callback function to be executed once after all tests within the current suite have completed.
2116
+ * This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files.
2117
+ *
2118
+ * **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
2119
+ *
2120
+ * @param {Function} fn - The callback function to be executed after all tests.
2121
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2122
+ * @returns {void}
2123
+ * @example
2124
+ * ```ts
2125
+ * // Example of using afterAll to close a database connection
2126
+ * afterAll(async () => {
2127
+ * await database.disconnect();
2128
+ * });
2129
+ * ```
2130
+ */
2131
+ function afterAll(fn, timeout) {
2132
+ assertTypes(fn, "\"afterAll\" callback", ["function"]);
2133
+ return getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR")));
2134
+ }
2135
+ /**
2136
+ * Registers a callback function to be executed before each test within the current suite.
2137
+ * This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables.
2138
+ *
2139
+ * **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
2140
+ *
2141
+ * @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
2142
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2143
+ * @returns {void}
2144
+ * @example
2145
+ * ```ts
2146
+ * // Example of using beforeEach to reset a database state
2147
+ * beforeEach(async () => {
2148
+ * await database.reset();
2149
+ * });
2150
+ * ```
2151
+ */
2152
+ function beforeEach(fn, timeout = getDefaultHookTimeout()) {
2153
+ assertTypes(fn, "\"beforeEach\" callback", ["function"]);
2154
+ const stackTraceError = new Error("STACK_TRACE_ERROR");
2155
+ const runner = getRunner();
2156
+ return getCurrentSuite().on("beforeEach", Object.assign(withTimeout(withFixtures(runner, fn), timeout ?? getDefaultHookTimeout(), true, stackTraceError, abortIfTimeout), {
2157
+ [CLEANUP_TIMEOUT_KEY]: timeout,
2158
+ [CLEANUP_STACK_TRACE_KEY]: stackTraceError
2159
+ }));
2160
+ }
2161
+ /**
2162
+ * Registers a callback function to be executed after each test within the current suite has completed.
2163
+ * This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions.
2164
+ *
2165
+ * **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
2166
+ *
2167
+ * @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
2168
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2169
+ * @returns {void}
2170
+ * @example
2171
+ * ```ts
2172
+ * // Example of using afterEach to delete temporary files created during a test
2173
+ * afterEach(async () => {
2174
+ * await fileSystem.deleteTempFiles();
2175
+ * });
2176
+ * ```
2177
+ */
2178
+ function afterEach(fn, timeout) {
2179
+ assertTypes(fn, "\"afterEach\" callback", ["function"]);
2180
+ const runner = getRunner();
2181
+ return getCurrentSuite().on("afterEach", withTimeout(withFixtures(runner, fn), timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
2182
+ }
2183
+ /**
2184
+ * Registers a callback function to be executed when a test fails within the current suite.
2185
+ * This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics.
2186
+ *
2187
+ * **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
2188
+ *
2189
+ * @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors).
2190
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2191
+ * @throws {Error} Throws an error if the function is not called within a test.
2192
+ * @returns {void}
2193
+ * @example
2194
+ * ```ts
2195
+ * // Example of using onTestFailed to log failure details
2196
+ * onTestFailed(({ errors }) => {
2197
+ * console.log(`Test failed: ${test.name}`, errors);
2198
+ * });
2199
+ * ```
2200
+ */
2201
+ const onTestFailed = createTestHook("onTestFailed", (test, handler, timeout) => {
2202
+ test.onFailed || (test.onFailed = []);
2203
+ test.onFailed.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
2204
+ });
2205
+ /**
2206
+ * Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail).
2207
+ * This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources.
2208
+ *
2209
+ * This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`.
2210
+ *
2211
+ * **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
2212
+ *
2213
+ * **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call.
2214
+ *
2215
+ * @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status.
2216
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
2217
+ * @throws {Error} Throws an error if the function is not called within a test.
2218
+ * @returns {void}
2219
+ * @example
2220
+ * ```ts
2221
+ * // Example of using onTestFinished for cleanup
2222
+ * const db = await connectToDatabase();
2223
+ * onTestFinished(async () => {
2224
+ * await db.disconnect();
2225
+ * });
2226
+ * ```
2227
+ */
2228
+ const onTestFinished = createTestHook("onTestFinished", (test, handler, timeout) => {
2229
+ test.onFinished || (test.onFinished = []);
2230
+ test.onFinished.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
2231
+ });
2232
+ function createTestHook(name, handler) {
2233
+ return (fn, timeout) => {
2234
+ assertTypes(fn, `"${name}" callback`, ["function"]);
2235
+ const current = getCurrentTest();
2236
+ if (!current) {
2237
+ throw new Error(`Hook ${name}() can only be called inside a test`);
2238
+ }
2239
+ return handler(current, fn, timeout);
2240
+ };
2241
+ }
2242
+
2243
+ export { someTasksAreOnly as A, limitConcurrency as B, partitionSuiteChildren as C, getFullName as D, getNames as E, getSuites as F, getTasks as G, getTestName as H, getTests as I, hasFailed as J, hasTests as K, isAtomTest as L, isTestCase as M, afterAll as a, afterEach as b, beforeAll as c, beforeEach as d, onTestFinished as e, getHooks as f, getFn as g, setHooks as h, startTests as i, createTaskCollector as j, describe as k, getCurrentSuite as l, it as m, suite as n, onTestFailed as o, publicCollect as p, getCurrentTest as q, createChainable as r, setFn as s, test as t, updateTask as u, calculateSuiteHash as v, createFileTask as w, generateFileHash as x, generateHash as y, interpretTaskModes as z };