@vitest/runner 3.2.0-beta.3 → 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.
package/dist/index.js CHANGED
@@ -1,1701 +1,5 @@
1
- import { isObject, createDefer, toArray, isNegativeNaN, format, objectAttr, objDisplay, getSafeTimers, assertTypes, shuffle } from '@vitest/utils';
2
- import { parseSingleStack } from '@vitest/utils/source-map';
3
- import { c as createChainable, b as createFileTask, a as calculateSuiteHash, s as someTasksAreOnly, i as interpretTaskModes, l as limitConcurrency, p as partitionSuiteChildren, o as hasTests, n as hasFailed } from './chunk-tasks.js';
4
- import { processError } from '@vitest/utils/error';
1
+ export { a as afterAll, b as afterEach, c as beforeAll, d as beforeEach, p as collectTests, j as createTaskCollector, k as describe, l as getCurrentSuite, q as getCurrentTest, g as getFn, f as getHooks, m as it, o as onTestFailed, e as onTestFinished, s as setFn, h as setHooks, i as startTests, n as suite, t as test, u as updateTask } from './chunk-hooks.js';
5
2
  export { processError } from '@vitest/utils/error';
3
+ import '@vitest/utils';
4
+ import '@vitest/utils/source-map';
6
5
  import 'pathe';
7
-
8
- class PendingError extends Error {
9
- code = "VITEST_PENDING";
10
- taskId;
11
- constructor(message, task, note) {
12
- super(message);
13
- this.message = message;
14
- this.note = note;
15
- this.taskId = task.id;
16
- }
17
- }
18
- class TestRunAbortError extends Error {
19
- name = "TestRunAbortError";
20
- reason;
21
- constructor(message, reason) {
22
- super(message);
23
- this.reason = reason;
24
- }
25
- }
26
-
27
- // use WeakMap here to make the Test and Suite object serializable
28
- const fnMap = new WeakMap();
29
- const testFixtureMap = new WeakMap();
30
- const hooksMap = new WeakMap();
31
- function setFn(key, fn) {
32
- fnMap.set(key, fn);
33
- }
34
- function getFn(key) {
35
- return fnMap.get(key);
36
- }
37
- function setTestFixture(key, fixture) {
38
- testFixtureMap.set(key, fixture);
39
- }
40
- function getTestFixture(key) {
41
- return testFixtureMap.get(key);
42
- }
43
- function setHooks(key, hooks) {
44
- hooksMap.set(key, hooks);
45
- }
46
- function getHooks(key) {
47
- return hooksMap.get(key);
48
- }
49
-
50
- function mergeScopedFixtures(testFixtures, scopedFixtures) {
51
- const scopedFixturesMap = scopedFixtures.reduce((map, fixture) => {
52
- map[fixture.prop] = fixture;
53
- return map;
54
- }, {});
55
- const newFixtures = {};
56
- testFixtures.forEach((fixture) => {
57
- const useFixture = scopedFixturesMap[fixture.prop] || { ...fixture };
58
- newFixtures[useFixture.prop] = useFixture;
59
- });
60
- for (const fixtureKep in newFixtures) {
61
- var _fixture$deps;
62
- const fixture = newFixtures[fixtureKep];
63
- // if the fixture was define before the scope, then its dep
64
- // will reference the original fixture instead of the scope
65
- fixture.deps = (_fixture$deps = fixture.deps) === null || _fixture$deps === void 0 ? void 0 : _fixture$deps.map((dep) => newFixtures[dep.prop]);
66
- }
67
- return Object.values(newFixtures);
68
- }
69
- function mergeContextFixtures(fixtures, context, inject) {
70
- const fixtureOptionKeys = ["auto", "injected"];
71
- const fixtureArray = Object.entries(fixtures).map(([prop, value]) => {
72
- const fixtureItem = { value };
73
- if (Array.isArray(value) && value.length >= 2 && isObject(value[1]) && Object.keys(value[1]).some((key) => fixtureOptionKeys.includes(key))) {
74
- // fixture with options
75
- Object.assign(fixtureItem, value[1]);
76
- const userValue = value[0];
77
- fixtureItem.value = fixtureItem.injected ? inject(prop) ?? userValue : userValue;
78
- }
79
- fixtureItem.prop = prop;
80
- fixtureItem.isFn = typeof fixtureItem.value === "function";
81
- return fixtureItem;
82
- });
83
- if (Array.isArray(context.fixtures)) {
84
- context.fixtures = context.fixtures.concat(fixtureArray);
85
- } else {
86
- context.fixtures = fixtureArray;
87
- }
88
- // Update dependencies of fixture functions
89
- fixtureArray.forEach((fixture) => {
90
- if (fixture.isFn) {
91
- const usedProps = getUsedProps(fixture.value);
92
- if (usedProps.length) {
93
- fixture.deps = context.fixtures.filter(({ prop }) => prop !== fixture.prop && usedProps.includes(prop));
94
- }
95
- }
96
- });
97
- return context;
98
- }
99
- const fixtureValueMaps = new Map();
100
- const cleanupFnArrayMap = new Map();
101
- async function callFixtureCleanup(context) {
102
- const cleanupFnArray = cleanupFnArrayMap.get(context) ?? [];
103
- for (const cleanup of cleanupFnArray.reverse()) {
104
- await cleanup();
105
- }
106
- cleanupFnArrayMap.delete(context);
107
- }
108
- function withFixtures(fn, testContext) {
109
- return (hookContext) => {
110
- const context = hookContext || testContext;
111
- if (!context) {
112
- return fn({});
113
- }
114
- const fixtures = getTestFixture(context);
115
- if (!(fixtures === null || fixtures === void 0 ? void 0 : fixtures.length)) {
116
- return fn(context);
117
- }
118
- const usedProps = getUsedProps(fn);
119
- const hasAutoFixture = fixtures.some(({ auto }) => auto);
120
- if (!usedProps.length && !hasAutoFixture) {
121
- return fn(context);
122
- }
123
- if (!fixtureValueMaps.get(context)) {
124
- fixtureValueMaps.set(context, new Map());
125
- }
126
- const fixtureValueMap = fixtureValueMaps.get(context);
127
- if (!cleanupFnArrayMap.has(context)) {
128
- cleanupFnArrayMap.set(context, []);
129
- }
130
- const cleanupFnArray = cleanupFnArrayMap.get(context);
131
- const usedFixtures = fixtures.filter(({ prop, auto }) => auto || usedProps.includes(prop));
132
- const pendingFixtures = resolveDeps(usedFixtures);
133
- if (!pendingFixtures.length) {
134
- return fn(context);
135
- }
136
- async function resolveFixtures() {
137
- for (const fixture of pendingFixtures) {
138
- // fixture could be already initialized during "before" hook
139
- if (fixtureValueMap.has(fixture)) {
140
- continue;
141
- }
142
- const resolvedValue = fixture.isFn ? await resolveFixtureFunction(fixture.value, context, cleanupFnArray) : fixture.value;
143
- context[fixture.prop] = resolvedValue;
144
- fixtureValueMap.set(fixture, resolvedValue);
145
- cleanupFnArray.unshift(() => {
146
- fixtureValueMap.delete(fixture);
147
- });
148
- }
149
- }
150
- return resolveFixtures().then(() => fn(context));
151
- };
152
- }
153
- async function resolveFixtureFunction(fixtureFn, context, cleanupFnArray) {
154
- // wait for `use` call to extract fixture value
155
- const useFnArgPromise = createDefer();
156
- let isUseFnArgResolved = false;
157
- const fixtureReturn = fixtureFn(context, async (useFnArg) => {
158
- // extract `use` argument
159
- isUseFnArgResolved = true;
160
- useFnArgPromise.resolve(useFnArg);
161
- // suspend fixture teardown by holding off `useReturnPromise` resolution until cleanup
162
- const useReturnPromise = createDefer();
163
- cleanupFnArray.push(async () => {
164
- // start teardown by resolving `use` Promise
165
- useReturnPromise.resolve();
166
- // wait for finishing teardown
167
- await fixtureReturn;
168
- });
169
- await useReturnPromise;
170
- }).catch((e) => {
171
- // treat fixture setup error as test failure
172
- if (!isUseFnArgResolved) {
173
- useFnArgPromise.reject(e);
174
- return;
175
- }
176
- // otherwise re-throw to avoid silencing error during cleanup
177
- throw e;
178
- });
179
- return useFnArgPromise;
180
- }
181
- function resolveDeps(fixtures, depSet = new Set(), pendingFixtures = []) {
182
- fixtures.forEach((fixture) => {
183
- if (pendingFixtures.includes(fixture)) {
184
- return;
185
- }
186
- if (!fixture.isFn || !fixture.deps) {
187
- pendingFixtures.push(fixture);
188
- return;
189
- }
190
- if (depSet.has(fixture)) {
191
- throw new Error(`Circular fixture dependency detected: ${fixture.prop} <- ${[...depSet].reverse().map((d) => d.prop).join(" <- ")}`);
192
- }
193
- depSet.add(fixture);
194
- resolveDeps(fixture.deps, depSet, pendingFixtures);
195
- pendingFixtures.push(fixture);
196
- depSet.clear();
197
- });
198
- return pendingFixtures;
199
- }
200
- function getUsedProps(fn) {
201
- let fnString = fn.toString();
202
- // match lowered async function and strip it off
203
- // example code on esbuild-try https://esbuild.github.io/try/#YgAwLjI0LjAALS1zdXBwb3J0ZWQ6YXN5bmMtYXdhaXQ9ZmFsc2UAZQBlbnRyeS50cwBjb25zdCBvID0gewogIGYxOiBhc3luYyAoKSA9PiB7fSwKICBmMjogYXN5bmMgKGEpID0+IHt9LAogIGYzOiBhc3luYyAoYSwgYikgPT4ge30sCiAgZjQ6IGFzeW5jIGZ1bmN0aW9uKGEpIHt9LAogIGY1OiBhc3luYyBmdW5jdGlvbiBmZihhKSB7fSwKICBhc3luYyBmNihhKSB7fSwKCiAgZzE6IGFzeW5jICgpID0+IHt9LAogIGcyOiBhc3luYyAoeyBhIH0pID0+IHt9LAogIGczOiBhc3luYyAoeyBhIH0sIGIpID0+IHt9LAogIGc0OiBhc3luYyBmdW5jdGlvbiAoeyBhIH0pIHt9LAogIGc1OiBhc3luYyBmdW5jdGlvbiBnZyh7IGEgfSkge30sCiAgYXN5bmMgZzYoeyBhIH0pIHt9Cn0
204
- // __async(this, null, function*
205
- // __async(this, arguments, function*
206
- // __async(this, [_0, _1], function*
207
- if (/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString)) {
208
- fnString = fnString.split(/__async\((?:this|null),/)[1];
209
- }
210
- const match = fnString.match(/[^(]*\(([^)]*)/);
211
- if (!match) {
212
- return [];
213
- }
214
- const args = splitByComma(match[1]);
215
- if (!args.length) {
216
- return [];
217
- }
218
- let first = args[0];
219
- if ("__VITEST_FIXTURE_INDEX__" in fn) {
220
- first = args[fn.__VITEST_FIXTURE_INDEX__];
221
- if (!first) {
222
- return [];
223
- }
224
- }
225
- if (!(first.startsWith("{") && first.endsWith("}"))) {
226
- throw new Error(`The first argument inside a fixture must use object destructuring pattern, e.g. ({ test } => {}). Instead, received "${first}".`);
227
- }
228
- const _first = first.slice(1, -1).replace(/\s/g, "");
229
- const props = splitByComma(_first).map((prop) => {
230
- return prop.replace(/:.*|=.*/g, "");
231
- });
232
- const last = props.at(-1);
233
- if (last && last.startsWith("...")) {
234
- throw new Error(`Rest parameters are not supported in fixtures, received "${last}".`);
235
- }
236
- return props;
237
- }
238
- function splitByComma(s) {
239
- const result = [];
240
- const stack = [];
241
- let start = 0;
242
- for (let i = 0; i < s.length; i++) {
243
- if (s[i] === "{" || s[i] === "[") {
244
- stack.push(s[i] === "{" ? "}" : "]");
245
- } else if (s[i] === stack[stack.length - 1]) {
246
- stack.pop();
247
- } else if (!stack.length && s[i] === ",") {
248
- const token = s.substring(start, i).trim();
249
- if (token) {
250
- result.push(token);
251
- }
252
- start = i + 1;
253
- }
254
- }
255
- const lastToken = s.substring(start).trim();
256
- if (lastToken) {
257
- result.push(lastToken);
258
- }
259
- return result;
260
- }
261
-
262
- let _test;
263
- function setCurrentTest(test) {
264
- _test = test;
265
- }
266
- function getCurrentTest() {
267
- return _test;
268
- }
269
- const tests = [];
270
- function addRunningTest(test) {
271
- tests.push(test);
272
- return () => {
273
- tests.splice(tests.indexOf(test));
274
- };
275
- }
276
- function getRunningTests() {
277
- return tests;
278
- }
279
-
280
- /**
281
- * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
282
- * Suites can contain both tests and other suites, enabling complex test structures.
283
- *
284
- * @param {string} name - The name of the suite, used for identification and reporting.
285
- * @param {Function} fn - A function that defines the tests and suites within this suite.
286
- * @example
287
- * ```ts
288
- * // Define a suite with two tests
289
- * suite('Math operations', () => {
290
- * test('should add two numbers', () => {
291
- * expect(add(1, 2)).toBe(3);
292
- * });
293
- *
294
- * test('should subtract two numbers', () => {
295
- * expect(subtract(5, 2)).toBe(3);
296
- * });
297
- * });
298
- * ```
299
- * @example
300
- * ```ts
301
- * // Define nested suites
302
- * suite('String operations', () => {
303
- * suite('Trimming', () => {
304
- * test('should trim whitespace from start and end', () => {
305
- * expect(' hello '.trim()).toBe('hello');
306
- * });
307
- * });
308
- *
309
- * suite('Concatenation', () => {
310
- * test('should concatenate two strings', () => {
311
- * expect('hello' + ' ' + 'world').toBe('hello world');
312
- * });
313
- * });
314
- * });
315
- * ```
316
- */
317
- const suite = createSuite();
318
- /**
319
- * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
320
- *
321
- * @param {string | Function} name - The name of the test or a function that will be used as a test name.
322
- * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
323
- * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
324
- * @throws {Error} If called inside another test function.
325
- * @example
326
- * ```ts
327
- * // Define a simple test
328
- * test('should add two numbers', () => {
329
- * expect(add(1, 2)).toBe(3);
330
- * });
331
- * ```
332
- * @example
333
- * ```ts
334
- * // Define a test with options
335
- * test('should subtract two numbers', { retry: 3 }, () => {
336
- * expect(subtract(5, 2)).toBe(3);
337
- * });
338
- * ```
339
- */
340
- const test = createTest(function(name, optionsOrFn, optionsOrTest) {
341
- if (getCurrentTest()) {
342
- 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.");
343
- }
344
- getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
345
- });
346
- /**
347
- * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
348
- * Suites can contain both tests and other suites, enabling complex test structures.
349
- *
350
- * @param {string} name - The name of the suite, used for identification and reporting.
351
- * @param {Function} fn - A function that defines the tests and suites within this suite.
352
- * @example
353
- * ```ts
354
- * // Define a suite with two tests
355
- * describe('Math operations', () => {
356
- * test('should add two numbers', () => {
357
- * expect(add(1, 2)).toBe(3);
358
- * });
359
- *
360
- * test('should subtract two numbers', () => {
361
- * expect(subtract(5, 2)).toBe(3);
362
- * });
363
- * });
364
- * ```
365
- * @example
366
- * ```ts
367
- * // Define nested suites
368
- * describe('String operations', () => {
369
- * describe('Trimming', () => {
370
- * test('should trim whitespace from start and end', () => {
371
- * expect(' hello '.trim()).toBe('hello');
372
- * });
373
- * });
374
- *
375
- * describe('Concatenation', () => {
376
- * test('should concatenate two strings', () => {
377
- * expect('hello' + ' ' + 'world').toBe('hello world');
378
- * });
379
- * });
380
- * });
381
- * ```
382
- */
383
- const describe = suite;
384
- /**
385
- * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
386
- *
387
- * @param {string | Function} name - The name of the test or a function that will be used as a test name.
388
- * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
389
- * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
390
- * @throws {Error} If called inside another test function.
391
- * @example
392
- * ```ts
393
- * // Define a simple test
394
- * it('adds two numbers', () => {
395
- * expect(add(1, 2)).toBe(3);
396
- * });
397
- * ```
398
- * @example
399
- * ```ts
400
- * // Define a test with options
401
- * it('subtracts two numbers', { retry: 3 }, () => {
402
- * expect(subtract(5, 2)).toBe(3);
403
- * });
404
- * ```
405
- */
406
- const it = test;
407
- let runner;
408
- let defaultSuite;
409
- let currentTestFilepath;
410
- function assert(condition, message) {
411
- if (!condition) {
412
- throw new Error(`Vitest failed to find ${message}. This is a bug in Vitest. Please, open an issue with reproduction.`);
413
- }
414
- }
415
- function getDefaultSuite() {
416
- assert(defaultSuite, "the default suite");
417
- return defaultSuite;
418
- }
419
- function getTestFilepath() {
420
- return currentTestFilepath;
421
- }
422
- function getRunner() {
423
- assert(runner, "the runner");
424
- return runner;
425
- }
426
- function createDefaultSuite(runner) {
427
- const config = runner.config.sequence;
428
- const collector = suite("", { concurrent: config.concurrent }, () => {});
429
- // no parent suite for top-level tests
430
- delete collector.suite;
431
- return collector;
432
- }
433
- function clearCollectorContext(filepath, currentRunner) {
434
- if (!defaultSuite) {
435
- defaultSuite = createDefaultSuite(currentRunner);
436
- }
437
- runner = currentRunner;
438
- currentTestFilepath = filepath;
439
- collectorContext.tasks.length = 0;
440
- defaultSuite.clear();
441
- collectorContext.currentSuite = defaultSuite;
442
- }
443
- function getCurrentSuite() {
444
- const currentSuite = collectorContext.currentSuite || defaultSuite;
445
- assert(currentSuite, "the current suite");
446
- return currentSuite;
447
- }
448
- function createSuiteHooks() {
449
- return {
450
- beforeAll: [],
451
- afterAll: [],
452
- beforeEach: [],
453
- afterEach: []
454
- };
455
- }
456
- function parseArguments(optionsOrFn, optionsOrTest) {
457
- let options = {};
458
- let fn = () => {};
459
- // it('', () => {}, { retry: 2 })
460
- if (typeof optionsOrTest === "object") {
461
- // it('', { retry: 2 }, { retry: 3 })
462
- if (typeof optionsOrFn === "object") {
463
- throw new TypeError("Cannot use two objects as arguments. Please provide options and a function callback in that order.");
464
- }
465
- 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");
466
- options = optionsOrTest;
467
- } else if (typeof optionsOrTest === "number") {
468
- options = { timeout: optionsOrTest };
469
- } else if (typeof optionsOrFn === "object") {
470
- options = optionsOrFn;
471
- }
472
- if (typeof optionsOrFn === "function") {
473
- if (typeof optionsOrTest === "function") {
474
- throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options.");
475
- }
476
- fn = optionsOrFn;
477
- } else if (typeof optionsOrTest === "function") {
478
- fn = optionsOrTest;
479
- }
480
- return {
481
- options,
482
- handler: fn
483
- };
484
- }
485
- // implementations
486
- function createSuiteCollector(name, factory = () => {}, mode, each, suiteOptions, parentCollectorFixtures) {
487
- const tasks = [];
488
- let suite;
489
- initSuite(true);
490
- const task = function(name = "", options = {}) {
491
- var _collectorContext$cur;
492
- const timeout = (options === null || options === void 0 ? void 0 : options.timeout) ?? runner.config.testTimeout;
493
- const task = {
494
- id: "",
495
- name,
496
- suite: (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.suite,
497
- each: options.each,
498
- fails: options.fails,
499
- context: undefined,
500
- type: "test",
501
- file: undefined,
502
- timeout,
503
- retry: options.retry ?? runner.config.retry,
504
- repeats: options.repeats,
505
- mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run",
506
- meta: options.meta ?? Object.create(null)
507
- };
508
- const handler = options.handler;
509
- if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) {
510
- task.concurrent = true;
511
- }
512
- task.shuffle = suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle;
513
- const context = createTestContext(task, runner);
514
- // create test context
515
- Object.defineProperty(task, "context", {
516
- value: context,
517
- enumerable: false
518
- });
519
- setTestFixture(context, options.fixtures);
520
- // custom can be called from any place, let's assume the limit is 15 stacks
521
- const limit = Error.stackTraceLimit;
522
- Error.stackTraceLimit = 15;
523
- const stackTraceError = new Error("STACK_TRACE_ERROR");
524
- Error.stackTraceLimit = limit;
525
- if (handler) {
526
- setFn(task, withTimeout(withAwaitAsyncAssertions(withFixtures(handler, context), task), timeout, false, stackTraceError, (_, error) => abortIfTimeout([context], error)));
527
- }
528
- if (runner.config.includeTaskLocation) {
529
- const error = stackTraceError.stack;
530
- const stack = findTestFileStackTrace(error, task.each ?? false);
531
- if (stack) {
532
- task.location = stack;
533
- }
534
- }
535
- tasks.push(task);
536
- return task;
537
- };
538
- const test = createTest(function(name, optionsOrFn, optionsOrTest) {
539
- let { options, handler } = parseArguments(optionsOrFn, optionsOrTest);
540
- // inherit repeats, retry, timeout from suite
541
- if (typeof suiteOptions === "object") {
542
- options = Object.assign({}, suiteOptions, options);
543
- }
544
- // inherit concurrent / sequential from suite
545
- options.concurrent = this.concurrent || !this.sequential && (options === null || options === void 0 ? void 0 : options.concurrent);
546
- options.sequential = this.sequential || !this.concurrent && (options === null || options === void 0 ? void 0 : options.sequential);
547
- const test = task(formatName(name), {
548
- ...this,
549
- ...options,
550
- handler
551
- });
552
- test.type = "test";
553
- });
554
- let collectorFixtures = parentCollectorFixtures;
555
- const collector = {
556
- type: "collector",
557
- name,
558
- mode,
559
- suite,
560
- options: suiteOptions,
561
- test,
562
- tasks,
563
- collect,
564
- task,
565
- clear,
566
- on: addHook,
567
- fixtures() {
568
- return collectorFixtures;
569
- },
570
- scoped(fixtures) {
571
- const parsed = mergeContextFixtures(fixtures, { fixtures: collectorFixtures }, (key) => {
572
- var _getRunner$injectValu, _getRunner;
573
- return (_getRunner$injectValu = (_getRunner = getRunner()).injectValue) === null || _getRunner$injectValu === void 0 ? void 0 : _getRunner$injectValu.call(_getRunner, key);
574
- });
575
- if (parsed.fixtures) {
576
- collectorFixtures = parsed.fixtures;
577
- }
578
- }
579
- };
580
- function addHook(name, ...fn) {
581
- getHooks(suite)[name].push(...fn);
582
- }
583
- function initSuite(includeLocation) {
584
- var _collectorContext$cur2;
585
- if (typeof suiteOptions === "number") {
586
- suiteOptions = { timeout: suiteOptions };
587
- }
588
- suite = {
589
- id: "",
590
- type: "suite",
591
- name,
592
- suite: (_collectorContext$cur2 = collectorContext.currentSuite) === null || _collectorContext$cur2 === void 0 ? void 0 : _collectorContext$cur2.suite,
593
- mode,
594
- each,
595
- file: undefined,
596
- shuffle: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle,
597
- tasks: [],
598
- meta: Object.create(null),
599
- concurrent: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.concurrent
600
- };
601
- if (runner && includeLocation && runner.config.includeTaskLocation) {
602
- const limit = Error.stackTraceLimit;
603
- Error.stackTraceLimit = 15;
604
- const error = new Error("stacktrace").stack;
605
- Error.stackTraceLimit = limit;
606
- const stack = findTestFileStackTrace(error, suite.each ?? false);
607
- if (stack) {
608
- suite.location = stack;
609
- }
610
- }
611
- setHooks(suite, createSuiteHooks());
612
- }
613
- function clear() {
614
- tasks.length = 0;
615
- initSuite(false);
616
- }
617
- async function collect(file) {
618
- if (!file) {
619
- throw new TypeError("File is required to collect tasks.");
620
- }
621
- if (factory) {
622
- await runWithSuite(collector, () => factory(test));
623
- }
624
- const allChildren = [];
625
- for (const i of tasks) {
626
- allChildren.push(i.type === "collector" ? await i.collect(file) : i);
627
- }
628
- suite.file = file;
629
- suite.tasks = allChildren;
630
- allChildren.forEach((task) => {
631
- task.file = file;
632
- });
633
- return suite;
634
- }
635
- collectTask(collector);
636
- return collector;
637
- }
638
- function withAwaitAsyncAssertions(fn, task) {
639
- return async (...args) => {
640
- const fnResult = await fn(...args);
641
- // some async expect will be added to this array, in case user forget to await them
642
- if (task.promises) {
643
- const result = await Promise.allSettled(task.promises);
644
- const errors = result.map((r) => r.status === "rejected" ? r.reason : undefined).filter(Boolean);
645
- if (errors.length) {
646
- throw errors;
647
- }
648
- }
649
- return fnResult;
650
- };
651
- }
652
- function createSuite() {
653
- function suiteFn(name, factoryOrOptions, optionsOrFactory) {
654
- var _currentSuite$options;
655
- const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
656
- const currentSuite = collectorContext.currentSuite || defaultSuite;
657
- let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory);
658
- const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false;
659
- const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false;
660
- // inherit options from current suite
661
- options = {
662
- ...currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.options,
663
- ...options,
664
- 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)
665
- };
666
- // inherit concurrent / sequential from suite
667
- const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified;
668
- const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified;
669
- options.concurrent = isConcurrent && !isSequential;
670
- options.sequential = isSequential && !isConcurrent;
671
- return createSuiteCollector(formatName(name), factory, mode, this.each, options, currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fixtures());
672
- }
673
- suiteFn.each = function(cases, ...args) {
674
- const suite = this.withContext();
675
- this.setContext("each", true);
676
- if (Array.isArray(cases) && args.length) {
677
- cases = formatTemplateString(cases, args);
678
- }
679
- return (name, optionsOrFn, fnOrOptions) => {
680
- const _name = formatName(name);
681
- const arrayOnlyCases = cases.every(Array.isArray);
682
- const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
683
- const fnFirst = typeof optionsOrFn === "function" && typeof fnOrOptions === "object";
684
- cases.forEach((i, idx) => {
685
- const items = Array.isArray(i) ? i : [i];
686
- if (fnFirst) {
687
- if (arrayOnlyCases) {
688
- suite(formatTitle(_name, items, idx), () => handler(...items), options);
689
- } else {
690
- suite(formatTitle(_name, items, idx), () => handler(i), options);
691
- }
692
- } else {
693
- if (arrayOnlyCases) {
694
- suite(formatTitle(_name, items, idx), options, () => handler(...items));
695
- } else {
696
- suite(formatTitle(_name, items, idx), options, () => handler(i));
697
- }
698
- }
699
- });
700
- this.setContext("each", undefined);
701
- };
702
- };
703
- suiteFn.for = function(cases, ...args) {
704
- if (Array.isArray(cases) && args.length) {
705
- cases = formatTemplateString(cases, args);
706
- }
707
- return (name, optionsOrFn, fnOrOptions) => {
708
- const name_ = formatName(name);
709
- const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
710
- cases.forEach((item, idx) => {
711
- suite(formatTitle(name_, toArray(item), idx), options, () => handler(item));
712
- });
713
- };
714
- };
715
- suiteFn.skipIf = (condition) => condition ? suite.skip : suite;
716
- suiteFn.runIf = (condition) => condition ? suite : suite.skip;
717
- return createChainable([
718
- "concurrent",
719
- "sequential",
720
- "shuffle",
721
- "skip",
722
- "only",
723
- "todo"
724
- ], suiteFn);
725
- }
726
- function createTaskCollector(fn, context) {
727
- const taskFn = fn;
728
- taskFn.each = function(cases, ...args) {
729
- const test = this.withContext();
730
- this.setContext("each", true);
731
- if (Array.isArray(cases) && args.length) {
732
- cases = formatTemplateString(cases, args);
733
- }
734
- return (name, optionsOrFn, fnOrOptions) => {
735
- const _name = formatName(name);
736
- const arrayOnlyCases = cases.every(Array.isArray);
737
- const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
738
- const fnFirst = typeof optionsOrFn === "function" && typeof fnOrOptions === "object";
739
- cases.forEach((i, idx) => {
740
- const items = Array.isArray(i) ? i : [i];
741
- if (fnFirst) {
742
- if (arrayOnlyCases) {
743
- test(formatTitle(_name, items, idx), () => handler(...items), options);
744
- } else {
745
- test(formatTitle(_name, items, idx), () => handler(i), options);
746
- }
747
- } else {
748
- if (arrayOnlyCases) {
749
- test(formatTitle(_name, items, idx), options, () => handler(...items));
750
- } else {
751
- test(formatTitle(_name, items, idx), options, () => handler(i));
752
- }
753
- }
754
- });
755
- this.setContext("each", undefined);
756
- };
757
- };
758
- taskFn.for = function(cases, ...args) {
759
- const test = this.withContext();
760
- if (Array.isArray(cases) && args.length) {
761
- cases = formatTemplateString(cases, args);
762
- }
763
- return (name, optionsOrFn, fnOrOptions) => {
764
- const _name = formatName(name);
765
- const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
766
- cases.forEach((item, idx) => {
767
- // monkey-patch handler to allow parsing fixture
768
- const handlerWrapper = (ctx) => handler(item, ctx);
769
- handlerWrapper.__VITEST_FIXTURE_INDEX__ = 1;
770
- handlerWrapper.toString = () => handler.toString();
771
- test(formatTitle(_name, toArray(item), idx), options, handlerWrapper);
772
- });
773
- };
774
- };
775
- taskFn.skipIf = function(condition) {
776
- return condition ? this.skip : this;
777
- };
778
- taskFn.runIf = function(condition) {
779
- return condition ? this : this.skip;
780
- };
781
- taskFn.scoped = function(fixtures) {
782
- const collector = getCurrentSuite();
783
- collector.scoped(fixtures);
784
- };
785
- taskFn.extend = function(fixtures) {
786
- const _context = mergeContextFixtures(fixtures, context || {}, (key) => {
787
- var _getRunner$injectValu2, _getRunner2;
788
- return (_getRunner$injectValu2 = (_getRunner2 = getRunner()).injectValue) === null || _getRunner$injectValu2 === void 0 ? void 0 : _getRunner$injectValu2.call(_getRunner2, key);
789
- });
790
- return createTest(function fn(name, optionsOrFn, optionsOrTest) {
791
- const collector = getCurrentSuite();
792
- const scopedFixtures = collector.fixtures();
793
- const context = { ...this };
794
- if (scopedFixtures) {
795
- context.fixtures = mergeScopedFixtures(context.fixtures || [], scopedFixtures);
796
- }
797
- collector.test.fn.call(context, formatName(name), optionsOrFn, optionsOrTest);
798
- }, _context);
799
- };
800
- const _test = createChainable([
801
- "concurrent",
802
- "sequential",
803
- "skip",
804
- "only",
805
- "todo",
806
- "fails"
807
- ], taskFn);
808
- if (context) {
809
- _test.mergeContext(context);
810
- }
811
- return _test;
812
- }
813
- function createTest(fn, context) {
814
- return createTaskCollector(fn, context);
815
- }
816
- function formatName(name) {
817
- return typeof name === "string" ? name : typeof name === "function" ? name.name || "<anonymous>" : String(name);
818
- }
819
- function formatTitle(template, items, idx) {
820
- if (template.includes("%#") || template.includes("%$")) {
821
- // '%#' match index of the test case
822
- template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%");
823
- }
824
- const count = template.split("%").length - 1;
825
- if (template.includes("%f")) {
826
- const placeholders = template.match(/%f/g) || [];
827
- placeholders.forEach((_, i) => {
828
- if (isNegativeNaN(items[i]) || Object.is(items[i], -0)) {
829
- // Replace the i-th occurrence of '%f' with '-%f'
830
- let occurrence = 0;
831
- template = template.replace(/%f/g, (match) => {
832
- occurrence++;
833
- return occurrence === i + 1 ? "-%f" : match;
834
- });
835
- }
836
- });
837
- }
838
- let formatted = format(template, ...items.slice(0, count));
839
- const isObjectItem = isObject(items[0]);
840
- formatted = formatted.replace(/\$([$\w.]+)/g, (_, key) => {
841
- var _runner$config;
842
- const isArrayKey = /^\d+$/.test(key);
843
- if (!isObjectItem && !isArrayKey) {
844
- return `$${key}`;
845
- }
846
- const arrayElement = isArrayKey ? objectAttr(items, key) : undefined;
847
- const value = isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement;
848
- 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 });
849
- });
850
- return formatted;
851
- }
852
- function formatTemplateString(cases, args) {
853
- const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0];
854
- const res = [];
855
- for (let i = 0; i < Math.floor(args.length / header.length); i++) {
856
- const oneCase = {};
857
- for (let j = 0; j < header.length; j++) {
858
- oneCase[header[j]] = args[i * header.length + j];
859
- }
860
- res.push(oneCase);
861
- }
862
- return res;
863
- }
864
- function findTestFileStackTrace(error, each) {
865
- // first line is the error message
866
- const lines = error.split("\n").slice(1);
867
- for (const line of lines) {
868
- const stack = parseSingleStack(line);
869
- if (stack && stack.file === getTestFilepath()) {
870
- return {
871
- line: stack.line,
872
- column: each ? stack.column + 1 : stack.column
873
- };
874
- }
875
- }
876
- }
877
-
878
- const now$2 = Date.now;
879
- const collectorContext = {
880
- tasks: [],
881
- currentSuite: null
882
- };
883
- function collectTask(task) {
884
- var _collectorContext$cur;
885
- (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.tasks.push(task);
886
- }
887
- async function runWithSuite(suite, fn) {
888
- const prev = collectorContext.currentSuite;
889
- collectorContext.currentSuite = suite;
890
- await fn();
891
- collectorContext.currentSuite = prev;
892
- }
893
- function withTimeout(fn, timeout, isHook = false, stackTraceError, onTimeout) {
894
- if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) {
895
- return fn;
896
- }
897
- const { setTimeout, clearTimeout } = getSafeTimers();
898
- // this function name is used to filter error in test/cli/test/fails.test.ts
899
- return function runWithTimeout(...args) {
900
- const startTime = now$2();
901
- const runner = getRunner();
902
- runner._currentTaskStartTime = startTime;
903
- runner._currentTaskTimeout = timeout;
904
- return new Promise((resolve_, reject_) => {
905
- var _timer$unref;
906
- const timer = setTimeout(() => {
907
- clearTimeout(timer);
908
- rejectTimeoutError();
909
- }, timeout);
910
- // `unref` might not exist in browser
911
- (_timer$unref = timer.unref) === null || _timer$unref === void 0 ? void 0 : _timer$unref.call(timer);
912
- function rejectTimeoutError() {
913
- const error = makeTimeoutError(isHook, timeout, stackTraceError);
914
- onTimeout === null || onTimeout === void 0 ? void 0 : onTimeout(args, error);
915
- reject_(error);
916
- }
917
- function resolve(result) {
918
- runner._currentTaskStartTime = undefined;
919
- runner._currentTaskTimeout = undefined;
920
- clearTimeout(timer);
921
- // if test/hook took too long in microtask, setTimeout won't be triggered,
922
- // but we still need to fail the test, see
923
- // https://github.com/vitest-dev/vitest/issues/2920
924
- if (now$2() - startTime >= timeout) {
925
- rejectTimeoutError();
926
- return;
927
- }
928
- resolve_(result);
929
- }
930
- function reject(error) {
931
- runner._currentTaskStartTime = undefined;
932
- runner._currentTaskTimeout = undefined;
933
- clearTimeout(timer);
934
- reject_(error);
935
- }
936
- // sync test/hook will be caught by try/catch
937
- try {
938
- const result = fn(...args);
939
- // the result is a thenable, we don't wrap this in Promise.resolve
940
- // to avoid creating new promises
941
- if (typeof result === "object" && result != null && typeof result.then === "function") {
942
- result.then(resolve, reject);
943
- } else {
944
- resolve(result);
945
- }
946
- }
947
- // user sync test/hook throws an error
948
- catch (error) {
949
- reject(error);
950
- }
951
- });
952
- };
953
- }
954
- const abortControllers = new WeakMap();
955
- function abortIfTimeout([context], error) {
956
- if (context) {
957
- abortContextSignal(context, error);
958
- }
959
- }
960
- function abortContextSignal(context, error) {
961
- const abortController = abortControllers.get(context);
962
- abortController === null || abortController === void 0 ? void 0 : abortController.abort(error);
963
- }
964
- function createTestContext(test, runner) {
965
- var _runner$extendTaskCon;
966
- const context = function() {
967
- throw new Error("done() callback is deprecated, use promise instead");
968
- };
969
- let abortController = abortControllers.get(context);
970
- if (!abortController) {
971
- abortController = new AbortController();
972
- abortControllers.set(context, abortController);
973
- }
974
- context.signal = abortController.signal;
975
- context.task = test;
976
- context.skip = (condition, note) => {
977
- if (condition === false) {
978
- // do nothing
979
- return undefined;
980
- }
981
- test.result ?? (test.result = { state: "skip" });
982
- test.result.pending = true;
983
- throw new PendingError("test is skipped; abort execution", test, typeof condition === "string" ? condition : note);
984
- };
985
- context.onTestFailed = (handler, timeout) => {
986
- test.onFailed || (test.onFailed = []);
987
- test.onFailed.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
988
- };
989
- context.onTestFinished = (handler, timeout) => {
990
- test.onFinished || (test.onFinished = []);
991
- test.onFinished.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
992
- };
993
- return ((_runner$extendTaskCon = runner.extendTaskContext) === null || _runner$extendTaskCon === void 0 ? void 0 : _runner$extendTaskCon.call(runner, context)) || context;
994
- }
995
- function makeTimeoutError(isHook, timeout, stackTraceError) {
996
- 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"}".`;
997
- const error = new Error(message);
998
- if (stackTraceError === null || stackTraceError === void 0 ? void 0 : stackTraceError.stack) {
999
- error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message);
1000
- }
1001
- return error;
1002
- }
1003
-
1004
- function getDefaultHookTimeout() {
1005
- return getRunner().config.hookTimeout;
1006
- }
1007
- const CLEANUP_TIMEOUT_KEY = Symbol.for("VITEST_CLEANUP_TIMEOUT");
1008
- const CLEANUP_STACK_TRACE_KEY = Symbol.for("VITEST_CLEANUP_STACK_TRACE");
1009
- function getBeforeHookCleanupCallback(hook, result, context) {
1010
- if (typeof result === "function") {
1011
- const timeout = CLEANUP_TIMEOUT_KEY in hook && typeof hook[CLEANUP_TIMEOUT_KEY] === "number" ? hook[CLEANUP_TIMEOUT_KEY] : getDefaultHookTimeout();
1012
- const stackTraceError = CLEANUP_STACK_TRACE_KEY in hook && hook[CLEANUP_STACK_TRACE_KEY] instanceof Error ? hook[CLEANUP_STACK_TRACE_KEY] : undefined;
1013
- return withTimeout(result, timeout, true, stackTraceError, (_, error) => {
1014
- if (context) {
1015
- abortContextSignal(context, error);
1016
- }
1017
- });
1018
- }
1019
- }
1020
- /**
1021
- * Registers a callback function to be executed once before all tests within the current suite.
1022
- * 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.
1023
- *
1024
- * **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.
1025
- *
1026
- * @param {Function} fn - The callback function to be executed before all tests.
1027
- * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1028
- * @returns {void}
1029
- * @example
1030
- * ```ts
1031
- * // Example of using beforeAll to set up a database connection
1032
- * beforeAll(async () => {
1033
- * await database.connect();
1034
- * });
1035
- * ```
1036
- */
1037
- function beforeAll(fn, timeout = getDefaultHookTimeout()) {
1038
- assertTypes(fn, "\"beforeAll\" callback", ["function"]);
1039
- const stackTraceError = new Error("STACK_TRACE_ERROR");
1040
- return getCurrentSuite().on("beforeAll", Object.assign(withTimeout(fn, timeout, true, stackTraceError), {
1041
- [CLEANUP_TIMEOUT_KEY]: timeout,
1042
- [CLEANUP_STACK_TRACE_KEY]: stackTraceError
1043
- }));
1044
- }
1045
- /**
1046
- * Registers a callback function to be executed once after all tests within the current suite have completed.
1047
- * 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.
1048
- *
1049
- * **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.
1050
- *
1051
- * @param {Function} fn - The callback function to be executed after all tests.
1052
- * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1053
- * @returns {void}
1054
- * @example
1055
- * ```ts
1056
- * // Example of using afterAll to close a database connection
1057
- * afterAll(async () => {
1058
- * await database.disconnect();
1059
- * });
1060
- * ```
1061
- */
1062
- function afterAll(fn, timeout) {
1063
- assertTypes(fn, "\"afterAll\" callback", ["function"]);
1064
- return getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR")));
1065
- }
1066
- /**
1067
- * Registers a callback function to be executed before each test within the current suite.
1068
- * 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.
1069
- *
1070
- * **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.
1071
- *
1072
- * @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
1073
- * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1074
- * @returns {void}
1075
- * @example
1076
- * ```ts
1077
- * // Example of using beforeEach to reset a database state
1078
- * beforeEach(async () => {
1079
- * await database.reset();
1080
- * });
1081
- * ```
1082
- */
1083
- function beforeEach(fn, timeout = getDefaultHookTimeout()) {
1084
- assertTypes(fn, "\"beforeEach\" callback", ["function"]);
1085
- const stackTraceError = new Error("STACK_TRACE_ERROR");
1086
- return getCurrentSuite().on("beforeEach", Object.assign(withTimeout(withFixtures(fn), timeout ?? getDefaultHookTimeout(), true, stackTraceError, abortIfTimeout), {
1087
- [CLEANUP_TIMEOUT_KEY]: timeout,
1088
- [CLEANUP_STACK_TRACE_KEY]: stackTraceError
1089
- }));
1090
- }
1091
- /**
1092
- * Registers a callback function to be executed after each test within the current suite has completed.
1093
- * 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.
1094
- *
1095
- * **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.
1096
- *
1097
- * @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
1098
- * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1099
- * @returns {void}
1100
- * @example
1101
- * ```ts
1102
- * // Example of using afterEach to delete temporary files created during a test
1103
- * afterEach(async () => {
1104
- * await fileSystem.deleteTempFiles();
1105
- * });
1106
- * ```
1107
- */
1108
- function afterEach(fn, timeout) {
1109
- assertTypes(fn, "\"afterEach\" callback", ["function"]);
1110
- return getCurrentSuite().on("afterEach", withTimeout(withFixtures(fn), timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
1111
- }
1112
- /**
1113
- * Registers a callback function to be executed when a test fails within the current suite.
1114
- * This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics.
1115
- *
1116
- * **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.
1117
- *
1118
- * @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors).
1119
- * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1120
- * @throws {Error} Throws an error if the function is not called within a test.
1121
- * @returns {void}
1122
- * @example
1123
- * ```ts
1124
- * // Example of using onTestFailed to log failure details
1125
- * onTestFailed(({ errors }) => {
1126
- * console.log(`Test failed: ${test.name}`, errors);
1127
- * });
1128
- * ```
1129
- */
1130
- const onTestFailed = createTestHook("onTestFailed", (test, handler, timeout) => {
1131
- test.onFailed || (test.onFailed = []);
1132
- test.onFailed.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
1133
- });
1134
- /**
1135
- * Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail).
1136
- * This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources.
1137
- *
1138
- * 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`.
1139
- *
1140
- * **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.
1141
- *
1142
- * **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call.
1143
- *
1144
- * @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.
1145
- * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1146
- * @throws {Error} Throws an error if the function is not called within a test.
1147
- * @returns {void}
1148
- * @example
1149
- * ```ts
1150
- * // Example of using onTestFinished for cleanup
1151
- * const db = await connectToDatabase();
1152
- * onTestFinished(async () => {
1153
- * await db.disconnect();
1154
- * });
1155
- * ```
1156
- */
1157
- const onTestFinished = createTestHook("onTestFinished", (test, handler, timeout) => {
1158
- test.onFinished || (test.onFinished = []);
1159
- test.onFinished.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
1160
- });
1161
- function createTestHook(name, handler) {
1162
- return (fn, timeout) => {
1163
- assertTypes(fn, `"${name}" callback`, ["function"]);
1164
- const current = getCurrentTest();
1165
- if (!current) {
1166
- throw new Error(`Hook ${name}() can only be called inside a test`);
1167
- }
1168
- return handler(current, fn, timeout);
1169
- };
1170
- }
1171
-
1172
- async function runSetupFiles(config, files, runner) {
1173
- if (config.sequence.setupFiles === "parallel") {
1174
- await Promise.all(files.map(async (fsPath) => {
1175
- await runner.importFile(fsPath, "setup");
1176
- }));
1177
- } else {
1178
- for (const fsPath of files) {
1179
- await runner.importFile(fsPath, "setup");
1180
- }
1181
- }
1182
- }
1183
-
1184
- const now$1 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1185
- async function collectTests(specs, runner) {
1186
- const files = [];
1187
- const config = runner.config;
1188
- for (const spec of specs) {
1189
- var _runner$onCollectStar;
1190
- const filepath = typeof spec === "string" ? spec : spec.filepath;
1191
- const testLocations = typeof spec === "string" ? undefined : spec.testLocations;
1192
- const file = createFileTask(filepath, config.root, config.name, runner.pool);
1193
- file.shuffle = config.sequence.shuffle;
1194
- (_runner$onCollectStar = runner.onCollectStart) === null || _runner$onCollectStar === void 0 ? void 0 : _runner$onCollectStar.call(runner, file);
1195
- clearCollectorContext(filepath, runner);
1196
- try {
1197
- const setupFiles = toArray(config.setupFiles);
1198
- if (setupFiles.length) {
1199
- const setupStart = now$1();
1200
- await runSetupFiles(config, setupFiles, runner);
1201
- const setupEnd = now$1();
1202
- file.setupDuration = setupEnd - setupStart;
1203
- } else {
1204
- file.setupDuration = 0;
1205
- }
1206
- const collectStart = now$1();
1207
- await runner.importFile(filepath, "collect");
1208
- const defaultTasks = await getDefaultSuite().collect(file);
1209
- const fileHooks = createSuiteHooks();
1210
- mergeHooks(fileHooks, getHooks(defaultTasks));
1211
- for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) {
1212
- if (c.type === "test" || c.type === "suite") {
1213
- file.tasks.push(c);
1214
- } else if (c.type === "collector") {
1215
- const suite = await c.collect(file);
1216
- if (suite.name || suite.tasks.length) {
1217
- mergeHooks(fileHooks, getHooks(suite));
1218
- file.tasks.push(suite);
1219
- }
1220
- } else {
1221
- // check that types are exhausted
1222
- c;
1223
- }
1224
- }
1225
- setHooks(file, fileHooks);
1226
- file.collectDuration = now$1() - collectStart;
1227
- } catch (e) {
1228
- const error = processError(e);
1229
- file.result = {
1230
- state: "fail",
1231
- errors: [error]
1232
- };
1233
- }
1234
- calculateSuiteHash(file);
1235
- const hasOnlyTasks = someTasksAreOnly(file);
1236
- interpretTaskModes(file, config.testNamePattern, testLocations, hasOnlyTasks, false, config.allowOnly);
1237
- if (file.mode === "queued") {
1238
- file.mode = "run";
1239
- }
1240
- files.push(file);
1241
- }
1242
- return files;
1243
- }
1244
- function mergeHooks(baseHooks, hooks) {
1245
- for (const _key in hooks) {
1246
- const key = _key;
1247
- baseHooks[key].push(...hooks[key]);
1248
- }
1249
- return baseHooks;
1250
- }
1251
-
1252
- const now = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1253
- const unixNow = Date.now;
1254
- function updateSuiteHookState(task, name, state, runner) {
1255
- if (!task.result) {
1256
- task.result = { state: "run" };
1257
- }
1258
- if (!task.result.hooks) {
1259
- task.result.hooks = {};
1260
- }
1261
- const suiteHooks = task.result.hooks;
1262
- if (suiteHooks) {
1263
- suiteHooks[name] = state;
1264
- let event = state === "run" ? "before-hook-start" : "before-hook-end";
1265
- if (name === "afterAll" || name === "afterEach") {
1266
- event = state === "run" ? "after-hook-start" : "after-hook-end";
1267
- }
1268
- updateTask(event, task, runner);
1269
- }
1270
- }
1271
- function getSuiteHooks(suite, name, sequence) {
1272
- const hooks = getHooks(suite)[name];
1273
- if (sequence === "stack" && (name === "afterAll" || name === "afterEach")) {
1274
- return hooks.slice().reverse();
1275
- }
1276
- return hooks;
1277
- }
1278
- async function callTestHooks(runner, test, hooks, sequence) {
1279
- if (sequence === "stack") {
1280
- hooks = hooks.slice().reverse();
1281
- }
1282
- if (!hooks.length) {
1283
- return;
1284
- }
1285
- const context = test.context;
1286
- const onTestFailed = test.context.onTestFailed;
1287
- const onTestFinished = test.context.onTestFinished;
1288
- context.onTestFailed = () => {
1289
- throw new Error(`Cannot call "onTestFailed" inside a test hook.`);
1290
- };
1291
- context.onTestFinished = () => {
1292
- throw new Error(`Cannot call "onTestFinished" inside a test hook.`);
1293
- };
1294
- if (sequence === "parallel") {
1295
- try {
1296
- await Promise.all(hooks.map((fn) => fn(test.context)));
1297
- } catch (e) {
1298
- failTask(test.result, e, runner.config.diffOptions);
1299
- }
1300
- } else {
1301
- for (const fn of hooks) {
1302
- try {
1303
- await fn(test.context);
1304
- } catch (e) {
1305
- failTask(test.result, e, runner.config.diffOptions);
1306
- }
1307
- }
1308
- }
1309
- context.onTestFailed = onTestFailed;
1310
- context.onTestFinished = onTestFinished;
1311
- }
1312
- async function callSuiteHook(suite, currentTask, name, runner, args) {
1313
- const sequence = runner.config.sequence.hooks;
1314
- const callbacks = [];
1315
- // stop at file level
1316
- const parentSuite = "filepath" in suite ? null : suite.suite || suite.file;
1317
- if (name === "beforeEach" && parentSuite) {
1318
- callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args));
1319
- }
1320
- const hooks = getSuiteHooks(suite, name, sequence);
1321
- if (hooks.length > 0) {
1322
- updateSuiteHookState(currentTask, name, "run", runner);
1323
- }
1324
- async function runHook(hook) {
1325
- return getBeforeHookCleanupCallback(hook, await hook(...args), name === "beforeEach" ? args[0] : undefined);
1326
- }
1327
- if (sequence === "parallel") {
1328
- callbacks.push(...await Promise.all(hooks.map((hook) => runHook(hook))));
1329
- } else {
1330
- for (const hook of hooks) {
1331
- callbacks.push(await runHook(hook));
1332
- }
1333
- }
1334
- if (hooks.length > 0) {
1335
- updateSuiteHookState(currentTask, name, "pass", runner);
1336
- }
1337
- if (name === "afterEach" && parentSuite) {
1338
- callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args));
1339
- }
1340
- return callbacks;
1341
- }
1342
- const packs = new Map();
1343
- const eventsPacks = [];
1344
- const pendingTasksUpdates = [];
1345
- function sendTasksUpdate(runner) {
1346
- if (packs.size) {
1347
- var _runner$onTaskUpdate;
1348
- const taskPacks = Array.from(packs).map(([id, task]) => {
1349
- return [
1350
- id,
1351
- task[0],
1352
- task[1]
1353
- ];
1354
- });
1355
- const p = (_runner$onTaskUpdate = runner.onTaskUpdate) === null || _runner$onTaskUpdate === void 0 ? void 0 : _runner$onTaskUpdate.call(runner, taskPacks, eventsPacks);
1356
- if (p) {
1357
- pendingTasksUpdates.push(p);
1358
- // remove successful promise to not grow array indefnitely,
1359
- // but keep rejections so finishSendTasksUpdate can handle them
1360
- p.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p), 1), () => {});
1361
- }
1362
- eventsPacks.length = 0;
1363
- packs.clear();
1364
- }
1365
- }
1366
- async function finishSendTasksUpdate(runner) {
1367
- sendTasksUpdate(runner);
1368
- await Promise.all(pendingTasksUpdates);
1369
- }
1370
- function throttle(fn, ms) {
1371
- let last = 0;
1372
- return function(...args) {
1373
- const now = unixNow();
1374
- if (now - last > ms) {
1375
- last = now;
1376
- return fn.apply(this, args);
1377
- }
1378
- };
1379
- }
1380
- // throttle based on summary reporter's DURATION_UPDATE_INTERVAL_MS
1381
- const sendTasksUpdateThrottled = throttle(sendTasksUpdate, 100);
1382
- function updateTask(event, task, runner) {
1383
- eventsPacks.push([task.id, event]);
1384
- packs.set(task.id, [task.result, task.meta]);
1385
- sendTasksUpdateThrottled(runner);
1386
- }
1387
- async function callCleanupHooks(runner, cleanups) {
1388
- const sequence = runner.config.sequence.hooks;
1389
- if (sequence === "stack") {
1390
- cleanups = cleanups.slice().reverse();
1391
- }
1392
- if (sequence === "parallel") {
1393
- await Promise.all(cleanups.map(async (fn) => {
1394
- if (typeof fn !== "function") {
1395
- return;
1396
- }
1397
- await fn();
1398
- }));
1399
- } else {
1400
- for (const fn of cleanups) {
1401
- if (typeof fn !== "function") {
1402
- continue;
1403
- }
1404
- await fn();
1405
- }
1406
- }
1407
- }
1408
- async function runTest(test, runner) {
1409
- var _runner$onBeforeRunTa, _test$result, _runner$onAfterRunTas;
1410
- await ((_runner$onBeforeRunTa = runner.onBeforeRunTask) === null || _runner$onBeforeRunTa === void 0 ? void 0 : _runner$onBeforeRunTa.call(runner, test));
1411
- if (test.mode !== "run" && test.mode !== "queued") {
1412
- updateTask("test-prepare", test, runner);
1413
- updateTask("test-finished", test, runner);
1414
- return;
1415
- }
1416
- if (((_test$result = test.result) === null || _test$result === void 0 ? void 0 : _test$result.state) === "fail") {
1417
- // should not be possible to get here, I think this is just copy pasted from suite
1418
- // TODO: maybe someone fails tests in `beforeAll` hooks?
1419
- // https://github.com/vitest-dev/vitest/pull/7069
1420
- updateTask("test-failed-early", test, runner);
1421
- return;
1422
- }
1423
- const start = now();
1424
- test.result = {
1425
- state: "run",
1426
- startTime: unixNow(),
1427
- retryCount: 0
1428
- };
1429
- updateTask("test-prepare", test, runner);
1430
- const cleanupRunningTest = addRunningTest(test);
1431
- setCurrentTest(test);
1432
- const suite = test.suite || test.file;
1433
- const repeats = test.repeats ?? 0;
1434
- for (let repeatCount = 0; repeatCount <= repeats; repeatCount++) {
1435
- const retry = test.retry ?? 0;
1436
- for (let retryCount = 0; retryCount <= retry; retryCount++) {
1437
- var _test$result2, _test$result3;
1438
- let beforeEachCleanups = [];
1439
- try {
1440
- var _runner$onBeforeTryTa, _runner$onAfterTryTas;
1441
- await ((_runner$onBeforeTryTa = runner.onBeforeTryTask) === null || _runner$onBeforeTryTa === void 0 ? void 0 : _runner$onBeforeTryTa.call(runner, test, {
1442
- retry: retryCount,
1443
- repeats: repeatCount
1444
- }));
1445
- test.result.repeatCount = repeatCount;
1446
- beforeEachCleanups = await callSuiteHook(suite, test, "beforeEach", runner, [test.context, suite]);
1447
- if (runner.runTask) {
1448
- await runner.runTask(test);
1449
- } else {
1450
- const fn = getFn(test);
1451
- if (!fn) {
1452
- throw new Error("Test function is not found. Did you add it using `setFn`?");
1453
- }
1454
- await fn();
1455
- }
1456
- await ((_runner$onAfterTryTas = runner.onAfterTryTask) === null || _runner$onAfterTryTas === void 0 ? void 0 : _runner$onAfterTryTas.call(runner, test, {
1457
- retry: retryCount,
1458
- repeats: repeatCount
1459
- }));
1460
- if (test.result.state !== "fail") {
1461
- if (!test.repeats) {
1462
- test.result.state = "pass";
1463
- } else if (test.repeats && retry === retryCount) {
1464
- test.result.state = "pass";
1465
- }
1466
- }
1467
- } catch (e) {
1468
- failTask(test.result, e, runner.config.diffOptions);
1469
- }
1470
- try {
1471
- var _runner$onTaskFinishe;
1472
- await ((_runner$onTaskFinishe = runner.onTaskFinished) === null || _runner$onTaskFinishe === void 0 ? void 0 : _runner$onTaskFinishe.call(runner, test));
1473
- } catch (e) {
1474
- failTask(test.result, e, runner.config.diffOptions);
1475
- }
1476
- try {
1477
- await callSuiteHook(suite, test, "afterEach", runner, [test.context, suite]);
1478
- await callCleanupHooks(runner, beforeEachCleanups);
1479
- await callFixtureCleanup(test.context);
1480
- } catch (e) {
1481
- failTask(test.result, e, runner.config.diffOptions);
1482
- }
1483
- await callTestHooks(runner, test, test.onFinished || [], "stack");
1484
- if (test.result.state === "fail") {
1485
- await callTestHooks(runner, test, test.onFailed || [], runner.config.sequence.hooks);
1486
- }
1487
- test.onFailed = undefined;
1488
- test.onFinished = undefined;
1489
- // skipped with new PendingError
1490
- 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") {
1491
- var _test$result4;
1492
- test.mode = "skip";
1493
- test.result = {
1494
- state: "skip",
1495
- note: (_test$result4 = test.result) === null || _test$result4 === void 0 ? void 0 : _test$result4.note,
1496
- pending: true,
1497
- duration: now() - start
1498
- };
1499
- updateTask("test-finished", test, runner);
1500
- setCurrentTest(undefined);
1501
- cleanupRunningTest();
1502
- return;
1503
- }
1504
- if (test.result.state === "pass") {
1505
- break;
1506
- }
1507
- if (retryCount < retry) {
1508
- // reset state when retry test
1509
- test.result.state = "run";
1510
- test.result.retryCount = (test.result.retryCount ?? 0) + 1;
1511
- }
1512
- // update retry info
1513
- updateTask("test-retried", test, runner);
1514
- }
1515
- }
1516
- // if test is marked to be failed, flip the result
1517
- if (test.fails) {
1518
- if (test.result.state === "pass") {
1519
- const error = processError(new Error("Expect test to fail"));
1520
- test.result.state = "fail";
1521
- test.result.errors = [error];
1522
- } else {
1523
- test.result.state = "pass";
1524
- test.result.errors = undefined;
1525
- }
1526
- }
1527
- cleanupRunningTest();
1528
- setCurrentTest(undefined);
1529
- test.result.duration = now() - start;
1530
- await ((_runner$onAfterRunTas = runner.onAfterRunTask) === null || _runner$onAfterRunTas === void 0 ? void 0 : _runner$onAfterRunTas.call(runner, test));
1531
- updateTask("test-finished", test, runner);
1532
- }
1533
- function failTask(result, err, diffOptions) {
1534
- if (err instanceof PendingError) {
1535
- result.state = "skip";
1536
- result.note = err.note;
1537
- result.pending = true;
1538
- return;
1539
- }
1540
- result.state = "fail";
1541
- const errors = Array.isArray(err) ? err : [err];
1542
- for (const e of errors) {
1543
- const error = processError(e, diffOptions);
1544
- result.errors ?? (result.errors = []);
1545
- result.errors.push(error);
1546
- }
1547
- }
1548
- function markTasksAsSkipped(suite, runner) {
1549
- suite.tasks.forEach((t) => {
1550
- t.mode = "skip";
1551
- t.result = {
1552
- ...t.result,
1553
- state: "skip"
1554
- };
1555
- updateTask("test-finished", t, runner);
1556
- if (t.type === "suite") {
1557
- markTasksAsSkipped(t, runner);
1558
- }
1559
- });
1560
- }
1561
- async function runSuite(suite, runner) {
1562
- var _runner$onBeforeRunSu, _suite$result;
1563
- await ((_runner$onBeforeRunSu = runner.onBeforeRunSuite) === null || _runner$onBeforeRunSu === void 0 ? void 0 : _runner$onBeforeRunSu.call(runner, suite));
1564
- if (((_suite$result = suite.result) === null || _suite$result === void 0 ? void 0 : _suite$result.state) === "fail") {
1565
- markTasksAsSkipped(suite, runner);
1566
- // failed during collection
1567
- updateTask("suite-failed-early", suite, runner);
1568
- return;
1569
- }
1570
- const start = now();
1571
- const mode = suite.mode;
1572
- suite.result = {
1573
- state: mode === "skip" || mode === "todo" ? mode : "run",
1574
- startTime: unixNow()
1575
- };
1576
- updateTask("suite-prepare", suite, runner);
1577
- let beforeAllCleanups = [];
1578
- if (suite.mode === "skip") {
1579
- suite.result.state = "skip";
1580
- updateTask("suite-finished", suite, runner);
1581
- } else if (suite.mode === "todo") {
1582
- suite.result.state = "todo";
1583
- updateTask("suite-finished", suite, runner);
1584
- } else {
1585
- var _runner$onAfterRunSui;
1586
- try {
1587
- try {
1588
- beforeAllCleanups = await callSuiteHook(suite, suite, "beforeAll", runner, [suite]);
1589
- } catch (e) {
1590
- markTasksAsSkipped(suite, runner);
1591
- throw e;
1592
- }
1593
- if (runner.runSuite) {
1594
- await runner.runSuite(suite);
1595
- } else {
1596
- for (let tasksGroup of partitionSuiteChildren(suite)) {
1597
- if (tasksGroup[0].concurrent === true) {
1598
- await Promise.all(tasksGroup.map((c) => runSuiteChild(c, runner)));
1599
- } else {
1600
- const { sequence } = runner.config;
1601
- if (suite.shuffle) {
1602
- // run describe block independently from tests
1603
- const suites = tasksGroup.filter((group) => group.type === "suite");
1604
- const tests = tasksGroup.filter((group) => group.type === "test");
1605
- const groups = shuffle([suites, tests], sequence.seed);
1606
- tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed));
1607
- }
1608
- for (const c of tasksGroup) {
1609
- await runSuiteChild(c, runner);
1610
- }
1611
- }
1612
- }
1613
- }
1614
- } catch (e) {
1615
- failTask(suite.result, e, runner.config.diffOptions);
1616
- }
1617
- try {
1618
- await callSuiteHook(suite, suite, "afterAll", runner, [suite]);
1619
- await callCleanupHooks(runner, beforeAllCleanups);
1620
- } catch (e) {
1621
- failTask(suite.result, e, runner.config.diffOptions);
1622
- }
1623
- if (suite.mode === "run" || suite.mode === "queued") {
1624
- if (!runner.config.passWithNoTests && !hasTests(suite)) {
1625
- var _suite$result$errors;
1626
- suite.result.state = "fail";
1627
- if (!((_suite$result$errors = suite.result.errors) === null || _suite$result$errors === void 0 ? void 0 : _suite$result$errors.length)) {
1628
- const error = processError(new Error(`No test found in suite ${suite.name}`));
1629
- suite.result.errors = [error];
1630
- }
1631
- } else if (hasFailed(suite)) {
1632
- suite.result.state = "fail";
1633
- } else {
1634
- suite.result.state = "pass";
1635
- }
1636
- }
1637
- suite.result.duration = now() - start;
1638
- updateTask("suite-finished", suite, runner);
1639
- await ((_runner$onAfterRunSui = runner.onAfterRunSuite) === null || _runner$onAfterRunSui === void 0 ? void 0 : _runner$onAfterRunSui.call(runner, suite));
1640
- }
1641
- }
1642
- let limitMaxConcurrency;
1643
- async function runSuiteChild(c, runner) {
1644
- if (c.type === "test") {
1645
- return limitMaxConcurrency(() => runTest(c, runner));
1646
- } else if (c.type === "suite") {
1647
- return runSuite(c, runner);
1648
- }
1649
- }
1650
- async function runFiles(files, runner) {
1651
- limitMaxConcurrency ?? (limitMaxConcurrency = limitConcurrency(runner.config.maxConcurrency));
1652
- for (const file of files) {
1653
- if (!file.tasks.length && !runner.config.passWithNoTests) {
1654
- var _file$result;
1655
- 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)) {
1656
- const error = processError(new Error(`No test suite found in file ${file.filepath}`));
1657
- file.result = {
1658
- state: "fail",
1659
- errors: [error]
1660
- };
1661
- }
1662
- }
1663
- await runSuite(file, runner);
1664
- }
1665
- }
1666
- async function startTests(specs, runner) {
1667
- var _runner$cancel;
1668
- const cancel = (_runner$cancel = runner.cancel) === null || _runner$cancel === void 0 ? void 0 : _runner$cancel.bind(runner);
1669
- // Ideally, we need to have an event listener for this, but only have a runner here.
1670
- // Adding another onCancel felt wrong (maybe it needs to be refactored)
1671
- runner.cancel = (reason) => {
1672
- // We intentionally create only one error since there is only one test run that can be cancelled
1673
- const error = new TestRunAbortError("The test run was aborted by the user.", reason);
1674
- getRunningTests().forEach((test) => abortContextSignal(test.context, error));
1675
- return cancel === null || cancel === void 0 ? void 0 : cancel(reason);
1676
- };
1677
- try {
1678
- var _runner$onBeforeColle, _runner$onCollected, _runner$onBeforeRunFi, _runner$onAfterRunFil;
1679
- const paths = specs.map((f) => typeof f === "string" ? f : f.filepath);
1680
- await ((_runner$onBeforeColle = runner.onBeforeCollect) === null || _runner$onBeforeColle === void 0 ? void 0 : _runner$onBeforeColle.call(runner, paths));
1681
- const files = await collectTests(specs, runner);
1682
- await ((_runner$onCollected = runner.onCollected) === null || _runner$onCollected === void 0 ? void 0 : _runner$onCollected.call(runner, files));
1683
- await ((_runner$onBeforeRunFi = runner.onBeforeRunFiles) === null || _runner$onBeforeRunFi === void 0 ? void 0 : _runner$onBeforeRunFi.call(runner, files));
1684
- await runFiles(files, runner);
1685
- await ((_runner$onAfterRunFil = runner.onAfterRunFiles) === null || _runner$onAfterRunFil === void 0 ? void 0 : _runner$onAfterRunFil.call(runner, files));
1686
- await finishSendTasksUpdate(runner);
1687
- return files;
1688
- } finally {
1689
- runner.cancel = cancel;
1690
- }
1691
- }
1692
- async function publicCollect(specs, runner) {
1693
- var _runner$onBeforeColle2, _runner$onCollected2;
1694
- const paths = specs.map((f) => typeof f === "string" ? f : f.filepath);
1695
- await ((_runner$onBeforeColle2 = runner.onBeforeCollect) === null || _runner$onBeforeColle2 === void 0 ? void 0 : _runner$onBeforeColle2.call(runner, paths));
1696
- const files = await collectTests(specs, runner);
1697
- await ((_runner$onCollected2 = runner.onCollected) === null || _runner$onCollected2 === void 0 ? void 0 : _runner$onCollected2.call(runner, files));
1698
- return files;
1699
- }
1700
-
1701
- export { afterAll, afterEach, beforeAll, beforeEach, publicCollect as collectTests, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, onTestFailed, onTestFinished, setFn, setHooks, startTests, suite, test, updateTask };