vitest 0.27.2 → 0.28.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.
Files changed (64) hide show
  1. package/LICENSE.md +4 -93
  2. package/browser.d.ts +1 -1
  3. package/dist/browser.d.ts +11 -13
  4. package/dist/browser.js +10 -34
  5. package/dist/{chunk-api-setup.029198e3.js → chunk-api-setup.52751a38.js} +27 -12
  6. package/dist/chunk-constants.797d3ebf.js +42 -0
  7. package/dist/{chunk-env-node.787e9561.js → chunk-env-node.ffd1183b.js} +26 -0
  8. package/dist/{chunk-install-pkg.7b006b3e.js → chunk-install-pkg.cfd23146.js} +51 -11
  9. package/dist/chunk-integrations-coverage.48e6286b.js +3993 -0
  10. package/dist/chunk-integrations-globals.0d5f50f0.js +29 -0
  11. package/dist/chunk-integrations-run-once.38756e30.js +27 -0
  12. package/dist/chunk-integrations-utils.f1f6f1ed.js +118 -0
  13. package/dist/{chunk-node-git.125c9008.js → chunk-node-git.d9ad64ab.js} +6 -7
  14. package/dist/{chunk-snapshot-manager.ce714e21.js → chunk-node-pkg.dcdf4369.js} +12653 -9324
  15. package/dist/{chunk-runtime-mocker.58511c38.js → chunk-runtime-mocker.03017e8c.js} +14 -13
  16. package/dist/{chunk-runtime-rpc.d709e91b.js → chunk-runtime-rpc.9c0386cc.js} +3 -2
  17. package/dist/chunk-runtime-setup.d9302cfd.js +20 -0
  18. package/dist/chunk-snapshot-env.6457638e.js +11 -0
  19. package/dist/chunk-utils-base.977ae74f.js +77 -0
  20. package/dist/chunk-utils-env.860d90c2.js +6 -0
  21. package/dist/chunk-utils-global.442d1d33.js +73 -0
  22. package/dist/{chunk-utils-import.054ab315.js → chunk-utils-import.9911c99d.js} +3289 -169
  23. package/dist/chunk-utils-tasks.1b603032.js +103 -0
  24. package/dist/cli-wrapper.js +8 -6
  25. package/dist/cli.js +18 -15
  26. package/dist/config.cjs +10 -7
  27. package/dist/config.d.ts +22 -4
  28. package/dist/config.js +10 -8
  29. package/dist/entry.js +244 -28
  30. package/dist/env-afee91f0.d.ts +10 -0
  31. package/dist/environments.d.ts +7 -2
  32. package/dist/environments.js +1 -1
  33. package/dist/index.d.ts +160 -11
  34. package/dist/index.js +18 -18
  35. package/dist/loader.js +9 -8
  36. package/dist/node.d.ts +9 -7
  37. package/dist/node.js +20 -17
  38. package/dist/runners-chunk.js +215 -0
  39. package/dist/runners.d.ts +39 -0
  40. package/dist/runners.js +18 -0
  41. package/dist/spy.js +1 -2
  42. package/dist/suite.d.ts +2 -0
  43. package/dist/suite.js +2 -18
  44. package/dist/{types-d97c72c7.d.ts → types-c800444e.d.ts} +196 -437
  45. package/dist/{vendor-index.e6c27006.js → vendor-index.618ca5a1.js} +1078 -10
  46. package/dist/{vendor-index.b0346fe4.js → vendor-index.bdee400f.js} +1 -0
  47. package/dist/worker.js +17 -16
  48. package/package.json +22 -12
  49. package/runners.d.ts +1 -0
  50. package/suite.d.ts +1 -0
  51. package/dist/chunk-integrations-coverage.44413252.js +0 -240
  52. package/dist/chunk-integrations-globals.0024ce21.js +0 -27
  53. package/dist/chunk-mock-date.c543fa3e.js +0 -349
  54. package/dist/chunk-runtime-chain.2da9e75c.js +0 -2595
  55. package/dist/chunk-runtime-error.de671af0.js +0 -144
  56. package/dist/chunk-runtime-setup.35da9209.js +0 -649
  57. package/dist/chunk-utils-env.f4a39d2c.js +0 -228
  58. package/dist/chunk-utils-source-map.5f5d12cf.js +0 -408
  59. package/dist/chunk-utils-timers.52534f96.js +0 -3573
  60. package/dist/index-50755efe.d.ts +0 -258
  61. package/dist/vendor-index.451e37bc.js +0 -1071
  62. package/dist/vendor-index.723a074f.js +0 -102
  63. package/dist/vendor-index.9c919048.js +0 -61
  64. package/dist/vendor-index.9f20a9be.js +0 -6291
@@ -1,649 +0,0 @@
1
- import { performance } from 'perf_hooks';
2
- import { g as generateHash, c as calculateSuiteHash, s as someTasksAreOnly, i as interpretTaskModes, t as takeCoverageInsideWorker, p as pLimit } from './chunk-integrations-coverage.44413252.js';
3
- import { f as clearCollectorContext, h as defaultSuite, j as setHooks, k as getHooks, l as collectorContext, m as getBenchOptions, n as getFn, o as setState, p as getSnapshotClient, G as GLOBAL_EXPECT, q as getState } from './chunk-runtime-chain.2da9e75c.js';
4
- import { r as resetRunOnceCounter, i as index, v as vi, s as setCurrentTest } from './chunk-utils-import.054ab315.js';
5
- import { g as getWorkerState, R as RealDate, t as toArray, k as relativePath, h as isRunningInBenchmark, p as partitionSuiteChildren, l as shuffle, q as hasTests, u as hasFailed, v as createDefer, e as getFullName } from './chunk-mock-date.c543fa3e.js';
6
- import { r as rpc } from './chunk-runtime-rpc.d709e91b.js';
7
- import { p as processError } from './chunk-runtime-error.de671af0.js';
8
- import { installSourcemapsSupport } from 'vite-node/source-map';
9
- import { e as environments } from './chunk-env-node.787e9561.js';
10
- import { i as isNode, a as isBrowser } from './chunk-utils-env.f4a39d2c.js';
11
- import { b as safeClearTimeout, s as safeSetTimeout } from './chunk-utils-timers.52534f96.js';
12
-
13
- let globalSetup = false;
14
- async function setupGlobalEnv(config) {
15
- resetRunOnceCounter();
16
- Object.defineProperty(globalThis, "__vitest_index__", {
17
- value: index,
18
- enumerable: false
19
- });
20
- setupDefines(config.defines);
21
- if (globalSetup)
22
- return;
23
- require.extensions[".css"] = () => ({});
24
- require.extensions[".scss"] = () => ({});
25
- require.extensions[".sass"] = () => ({});
26
- globalSetup = true;
27
- if (isNode) {
28
- const state = getWorkerState();
29
- installSourcemapsSupport({
30
- getSourceMap: (source) => state.moduleCache.getSourceMap(source)
31
- });
32
- await setupConsoleLogSpy();
33
- }
34
- if (config.globals)
35
- (await import('./chunk-integrations-globals.0024ce21.js')).registerApiGlobally();
36
- }
37
- function setupDefines(defines) {
38
- for (const key in defines)
39
- globalThis[key] = defines[key];
40
- }
41
- async function setupConsoleLogSpy() {
42
- const stdoutBuffer = /* @__PURE__ */ new Map();
43
- const stderrBuffer = /* @__PURE__ */ new Map();
44
- const timers = /* @__PURE__ */ new Map();
45
- const unknownTestId = "__vitest__unknown_test__";
46
- const { Writable } = await import('node:stream');
47
- const { Console } = await import('node:console');
48
- function schedule(taskId) {
49
- const timer = timers.get(taskId);
50
- const { stdoutTime, stderrTime } = timer;
51
- safeClearTimeout(timer.timer);
52
- timer.timer = safeSetTimeout(() => {
53
- if (stderrTime < stdoutTime) {
54
- sendStderr(taskId);
55
- sendStdout(taskId);
56
- } else {
57
- sendStdout(taskId);
58
- sendStderr(taskId);
59
- }
60
- });
61
- }
62
- function sendStdout(taskId) {
63
- const buffer = stdoutBuffer.get(taskId);
64
- if (!buffer)
65
- return;
66
- const content = buffer.map((i) => String(i)).join("");
67
- if (!content.trim())
68
- return;
69
- const timer = timers.get(taskId);
70
- rpc().onUserConsoleLog({
71
- type: "stdout",
72
- content,
73
- taskId,
74
- time: timer.stdoutTime || RealDate.now(),
75
- size: buffer.length
76
- });
77
- stdoutBuffer.set(taskId, []);
78
- timer.stdoutTime = 0;
79
- }
80
- function sendStderr(taskId) {
81
- const buffer = stderrBuffer.get(taskId);
82
- if (!buffer)
83
- return;
84
- const content = buffer.map((i) => String(i)).join("");
85
- if (!content.trim())
86
- return;
87
- const timer = timers.get(taskId);
88
- rpc().onUserConsoleLog({
89
- type: "stderr",
90
- content,
91
- taskId,
92
- time: timer.stderrTime || RealDate.now(),
93
- size: buffer.length
94
- });
95
- stderrBuffer.set(taskId, []);
96
- timer.stderrTime = 0;
97
- }
98
- const stdout = new Writable({
99
- write(data, encoding, callback) {
100
- var _a, _b;
101
- const id = ((_b = (_a = getWorkerState()) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
102
- let timer = timers.get(id);
103
- if (timer) {
104
- timer.stdoutTime = timer.stdoutTime || RealDate.now();
105
- } else {
106
- timer = { stdoutTime: RealDate.now(), stderrTime: RealDate.now(), timer: 0 };
107
- timers.set(id, timer);
108
- }
109
- let buffer = stdoutBuffer.get(id);
110
- if (!buffer) {
111
- buffer = [];
112
- stdoutBuffer.set(id, buffer);
113
- }
114
- buffer.push(data);
115
- schedule(id);
116
- callback();
117
- }
118
- });
119
- const stderr = new Writable({
120
- write(data, encoding, callback) {
121
- var _a, _b;
122
- const id = ((_b = (_a = getWorkerState()) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
123
- let timer = timers.get(id);
124
- if (timer) {
125
- timer.stderrTime = timer.stderrTime || RealDate.now();
126
- } else {
127
- timer = { stderrTime: RealDate.now(), stdoutTime: RealDate.now(), timer: 0 };
128
- timers.set(id, timer);
129
- }
130
- let buffer = stderrBuffer.get(id);
131
- if (!buffer) {
132
- buffer = [];
133
- stderrBuffer.set(id, buffer);
134
- }
135
- buffer.push(data);
136
- schedule(id);
137
- callback();
138
- }
139
- });
140
- globalThis.console = new Console({
141
- stdout,
142
- stderr,
143
- colorMode: true,
144
- groupIndentation: 2
145
- });
146
- }
147
- async function loadEnvironment(name) {
148
- const pkg = await import(`vitest-environment-${name}`);
149
- if (!pkg || !pkg.default || typeof pkg.default !== "object" || typeof pkg.default.setup !== "function") {
150
- throw new Error(
151
- `Environment "${name}" is not a valid environment. Package "vitest-environment-${name}" should have default export with "setup" method.`
152
- );
153
- }
154
- return pkg.default;
155
- }
156
- async function withEnv(name, options, fn) {
157
- const config = environments[name] || await loadEnvironment(name);
158
- const env = await config.setup(globalThis, options);
159
- try {
160
- await fn();
161
- } finally {
162
- await env.teardown(globalThis);
163
- }
164
- }
165
- async function runSetupFiles(config) {
166
- const files = toArray(config.setupFiles);
167
- await Promise.all(
168
- files.map(async (fsPath) => {
169
- getWorkerState().moduleCache.delete(fsPath);
170
- await import(fsPath);
171
- })
172
- );
173
- }
174
-
175
- const now$1 = Date.now;
176
- async function collectTests(paths, config) {
177
- const files = [];
178
- const browserHashMap = getWorkerState().browserHashMap;
179
- async function importFromBrowser(filepath) {
180
- const match = filepath.match(/^(\w:\/)/);
181
- const hash = browserHashMap.get(filepath);
182
- if (match)
183
- return await import(`/@fs/${filepath.slice(match[1].length)}?v=${hash}`);
184
- else
185
- return await import(`${filepath}?v=${hash}`);
186
- }
187
- for (const filepath of paths) {
188
- const path = relativePath(config.root, filepath);
189
- const file = {
190
- id: generateHash(path),
191
- name: path,
192
- type: "suite",
193
- mode: "run",
194
- filepath,
195
- tasks: [],
196
- projectName: config.name
197
- };
198
- clearCollectorContext();
199
- try {
200
- const setupStart = now$1();
201
- await runSetupFiles(config);
202
- const collectStart = now$1();
203
- file.setupDuration = collectStart - setupStart;
204
- if (config.browser && isBrowser)
205
- await importFromBrowser(filepath);
206
- else
207
- await import(filepath);
208
- const defaultTasks = await defaultSuite.collect(file);
209
- setHooks(file, getHooks(defaultTasks));
210
- for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) {
211
- if (c.type === "test") {
212
- file.tasks.push(c);
213
- } else if (c.type === "benchmark") {
214
- file.tasks.push(c);
215
- } else if (c.type === "suite") {
216
- file.tasks.push(c);
217
- } else if (c.type === "collector") {
218
- const suite = await c.collect(file);
219
- if (suite.name || suite.tasks.length)
220
- file.tasks.push(suite);
221
- }
222
- }
223
- file.collectDuration = now$1() - collectStart;
224
- } catch (e) {
225
- const error = processError(e);
226
- file.result = {
227
- state: "fail",
228
- error,
229
- errors: [error]
230
- };
231
- if (config.browser)
232
- console.error(e);
233
- }
234
- calculateSuiteHash(file);
235
- const hasOnlyTasks = someTasksAreOnly(file);
236
- interpretTaskModes(file, config.testNamePattern, hasOnlyTasks, false, config.allowOnly);
237
- files.push(file);
238
- }
239
- return files;
240
- }
241
-
242
- async function importTinybench() {
243
- if (!globalThis.EventTarget)
244
- await import('./vendor-index.534e612c.js').then(function (n) { return n.i; });
245
- return await import('tinybench');
246
- }
247
- const now = Date.now;
248
- function updateSuiteHookState(suite, name, state) {
249
- var _a;
250
- if (!suite.result)
251
- suite.result = { state: "run" };
252
- if (!((_a = suite.result) == null ? void 0 : _a.hooks))
253
- suite.result.hooks = {};
254
- const suiteHooks = suite.result.hooks;
255
- if (suiteHooks) {
256
- suiteHooks[name] = state;
257
- updateTask(suite);
258
- }
259
- }
260
- function getSuiteHooks(suite, name, sequence) {
261
- const hooks = getHooks(suite)[name];
262
- if (sequence === "stack" && (name === "afterAll" || name === "afterEach"))
263
- return hooks.slice().reverse();
264
- return hooks;
265
- }
266
- async function callSuiteHook(suite, currentTask, name, args) {
267
- const callbacks = [];
268
- if (name === "beforeEach" && suite.suite) {
269
- callbacks.push(
270
- ...await callSuiteHook(suite.suite, currentTask, name, args)
271
- );
272
- }
273
- updateSuiteHookState(currentTask, name, "run");
274
- const state = getWorkerState();
275
- const sequence = state.config.sequence.hooks;
276
- const hooks = getSuiteHooks(suite, name, sequence);
277
- if (sequence === "parallel") {
278
- callbacks.push(...await Promise.all(hooks.map((fn) => fn(...args))));
279
- } else {
280
- for (const hook of hooks)
281
- callbacks.push(await hook(...args));
282
- }
283
- updateSuiteHookState(currentTask, name, "pass");
284
- if (name === "afterEach" && suite.suite) {
285
- callbacks.push(
286
- ...await callSuiteHook(suite.suite, currentTask, name, args)
287
- );
288
- }
289
- return callbacks;
290
- }
291
- const packs = /* @__PURE__ */ new Map();
292
- let updateTimer;
293
- let previousUpdate;
294
- function updateTask(task) {
295
- packs.set(task.id, task.result);
296
- safeClearTimeout(updateTimer);
297
- updateTimer = safeSetTimeout(() => {
298
- previousUpdate = sendTasksUpdate();
299
- }, 10);
300
- }
301
- async function sendTasksUpdate() {
302
- safeClearTimeout(updateTimer);
303
- await previousUpdate;
304
- if (packs.size) {
305
- const p = rpc().onTaskUpdate(Array.from(packs));
306
- packs.clear();
307
- return p;
308
- }
309
- }
310
- const callCleanupHooks = async (cleanups) => {
311
- await Promise.all(cleanups.map(async (fn) => {
312
- if (typeof fn !== "function")
313
- return;
314
- await fn();
315
- }));
316
- };
317
- async function runTest(test) {
318
- var _a, _b, _c;
319
- if (test.mode !== "run") {
320
- const { getSnapshotClient: getSnapshotClient2 } = await import('./chunk-runtime-chain.2da9e75c.js').then(function (n) { return n.u; });
321
- getSnapshotClient2().skipTestSnapshots(test);
322
- return;
323
- }
324
- if (((_a = test.result) == null ? void 0 : _a.state) === "fail") {
325
- updateTask(test);
326
- return;
327
- }
328
- const start = now();
329
- test.result = {
330
- state: "run",
331
- startTime: start
332
- };
333
- updateTask(test);
334
- clearModuleMocks();
335
- setCurrentTest(test);
336
- if (isNode) {
337
- const { getSnapshotClient: getSnapshotClient2 } = await import('./chunk-runtime-chain.2da9e75c.js').then(function (n) { return n.u; });
338
- await getSnapshotClient2().setTest(test);
339
- }
340
- const workerState = getWorkerState();
341
- workerState.current = test;
342
- const retry = test.retry || 1;
343
- for (let retryCount = 0; retryCount < retry; retryCount++) {
344
- let beforeEachCleanups = [];
345
- try {
346
- setState({
347
- assertionCalls: 0,
348
- isExpectingAssertions: false,
349
- isExpectingAssertionsError: null,
350
- expectedAssertionsNumber: null,
351
- expectedAssertionsNumberErrorGen: null,
352
- testPath: (_b = test.suite.file) == null ? void 0 : _b.filepath,
353
- currentTestName: getFullName(test),
354
- snapshotState: getSnapshotClient().snapshotState
355
- }, globalThis[GLOBAL_EXPECT]);
356
- beforeEachCleanups = await callSuiteHook(test.suite, test, "beforeEach", [test.context, test.suite]);
357
- test.result.retryCount = retryCount;
358
- await getFn(test)();
359
- const {
360
- assertionCalls,
361
- expectedAssertionsNumber,
362
- expectedAssertionsNumberErrorGen,
363
- isExpectingAssertions,
364
- isExpectingAssertionsError
365
- } = test.context._local ? test.context.expect.getState() : getState(globalThis[GLOBAL_EXPECT]);
366
- if (expectedAssertionsNumber !== null && assertionCalls !== expectedAssertionsNumber)
367
- throw expectedAssertionsNumberErrorGen();
368
- if (isExpectingAssertions === true && assertionCalls === 0)
369
- throw isExpectingAssertionsError;
370
- test.result.state = "pass";
371
- } catch (e) {
372
- const error = processError(e);
373
- test.result.state = "fail";
374
- test.result.error = error;
375
- test.result.errors = [error];
376
- }
377
- try {
378
- await callSuiteHook(test.suite, test, "afterEach", [test.context, test.suite]);
379
- await callCleanupHooks(beforeEachCleanups);
380
- } catch (e) {
381
- const error = processError(e);
382
- test.result.state = "fail";
383
- test.result.error = error;
384
- test.result.errors = [error];
385
- }
386
- if (test.result.state === "pass")
387
- break;
388
- updateTask(test);
389
- }
390
- if (test.result.state === "fail")
391
- await Promise.all(((_c = test.onFailed) == null ? void 0 : _c.map((fn) => fn(test.result))) || []);
392
- if (test.fails) {
393
- if (test.result.state === "pass") {
394
- const error = processError(new Error("Expect test to fail"));
395
- test.result.state = "fail";
396
- test.result.error = error;
397
- test.result.errors = [error];
398
- } else {
399
- test.result.state = "pass";
400
- test.result.error = void 0;
401
- test.result.errors = void 0;
402
- }
403
- }
404
- if (isBrowser && test.result.error)
405
- console.error(test.result.error.message, test.result.error.stackStr);
406
- setCurrentTest(void 0);
407
- if (isNode) {
408
- const { getSnapshotClient: getSnapshotClient2 } = await import('./chunk-runtime-chain.2da9e75c.js').then(function (n) { return n.u; });
409
- getSnapshotClient2().clearTest();
410
- }
411
- test.result.duration = now() - start;
412
- if (workerState.config.logHeapUsage && isNode)
413
- test.result.heap = process.memoryUsage().heapUsed;
414
- workerState.current = void 0;
415
- updateTask(test);
416
- }
417
- function markTasksAsSkipped(suite) {
418
- suite.tasks.forEach((t) => {
419
- t.mode = "skip";
420
- t.result = { ...t.result, state: "skip" };
421
- updateTask(t);
422
- if (t.type === "suite")
423
- markTasksAsSkipped(t);
424
- });
425
- }
426
- async function runSuite(suite) {
427
- var _a;
428
- if (((_a = suite.result) == null ? void 0 : _a.state) === "fail") {
429
- markTasksAsSkipped(suite);
430
- updateTask(suite);
431
- return;
432
- }
433
- const start = now();
434
- suite.result = {
435
- state: "run",
436
- startTime: start
437
- };
438
- updateTask(suite);
439
- const workerState = getWorkerState();
440
- if (suite.mode === "skip") {
441
- suite.result.state = "skip";
442
- } else if (suite.mode === "todo") {
443
- suite.result.state = "todo";
444
- } else {
445
- try {
446
- const beforeAllCleanups = await callSuiteHook(suite, suite, "beforeAll", [suite]);
447
- if (isRunningInBenchmark()) {
448
- await runBenchmarkSuite(suite);
449
- } else {
450
- for (let tasksGroup of partitionSuiteChildren(suite)) {
451
- if (tasksGroup[0].concurrent === true) {
452
- const mutex = pLimit(workerState.config.maxConcurrency);
453
- await Promise.all(tasksGroup.map((c) => mutex(() => runSuiteChild(c))));
454
- } else {
455
- const { sequence } = workerState.config;
456
- if (sequence.shuffle || suite.shuffle) {
457
- const suites = tasksGroup.filter((group) => group.type === "suite");
458
- const tests = tasksGroup.filter((group) => group.type === "test");
459
- const groups = shuffle([suites, tests], sequence.seed);
460
- tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed));
461
- }
462
- for (const c of tasksGroup)
463
- await runSuiteChild(c);
464
- }
465
- }
466
- }
467
- await callSuiteHook(suite, suite, "afterAll", [suite]);
468
- await callCleanupHooks(beforeAllCleanups);
469
- } catch (e) {
470
- const error = processError(e);
471
- suite.result.state = "fail";
472
- suite.result.error = error;
473
- suite.result.errors = [error];
474
- }
475
- }
476
- suite.result.duration = now() - start;
477
- if (workerState.config.logHeapUsage && isNode)
478
- suite.result.heap = process.memoryUsage().heapUsed;
479
- if (suite.mode === "run") {
480
- if (!hasTests(suite)) {
481
- suite.result.state = "fail";
482
- if (!suite.result.error) {
483
- const error = processError(new Error(`No test found in suite ${suite.name}`));
484
- suite.result.error = error;
485
- suite.result.errors = [error];
486
- }
487
- } else if (hasFailed(suite)) {
488
- suite.result.state = "fail";
489
- } else {
490
- suite.result.state = "pass";
491
- }
492
- }
493
- updateTask(suite);
494
- }
495
- function createBenchmarkResult(name) {
496
- return {
497
- name,
498
- rank: 0,
499
- rme: 0,
500
- samples: []
501
- };
502
- }
503
- async function runBenchmarkSuite(suite) {
504
- const { Task, Bench } = await importTinybench();
505
- const start = performance.now();
506
- const benchmarkGroup = [];
507
- const benchmarkSuiteGroup = [];
508
- for (const task of suite.tasks) {
509
- if (task.mode !== "run")
510
- continue;
511
- if (task.type === "benchmark")
512
- benchmarkGroup.push(task);
513
- else if (task.type === "suite")
514
- benchmarkSuiteGroup.push(task);
515
- }
516
- if (benchmarkSuiteGroup.length)
517
- await Promise.all(benchmarkSuiteGroup.map((subSuite) => runBenchmarkSuite(subSuite)));
518
- if (benchmarkGroup.length) {
519
- const defer = createDefer();
520
- const benchmarkMap = {};
521
- suite.result = {
522
- state: "run",
523
- startTime: start,
524
- benchmark: createBenchmarkResult(suite.name)
525
- };
526
- updateTask(suite);
527
- benchmarkGroup.forEach((benchmark, idx) => {
528
- const options = getBenchOptions(benchmark);
529
- const benchmarkInstance = new Bench(options);
530
- const benchmarkFn = getFn(benchmark);
531
- benchmark.result = {
532
- state: "run",
533
- startTime: start,
534
- benchmark: createBenchmarkResult(benchmark.name)
535
- };
536
- const id = idx.toString();
537
- benchmarkMap[id] = benchmark;
538
- const task = new Task(benchmarkInstance, id, benchmarkFn);
539
- benchmark.task = task;
540
- updateTask(benchmark);
541
- });
542
- benchmarkGroup.forEach((benchmark) => {
543
- benchmark.task.addEventListener("complete", (e) => {
544
- const task = e.task;
545
- const _benchmark = benchmarkMap[task.name || ""];
546
- if (_benchmark) {
547
- const taskRes = task.result;
548
- const result = _benchmark.result.benchmark;
549
- Object.assign(result, taskRes);
550
- updateTask(_benchmark);
551
- }
552
- });
553
- benchmark.task.addEventListener("error", (e) => {
554
- const task = e.task;
555
- const _benchmark = benchmarkMap[task.name || ""];
556
- defer.reject(_benchmark ? task.result.error : e);
557
- });
558
- });
559
- Promise.all(benchmarkGroup.map(async (benchmark) => {
560
- await benchmark.task.warmup();
561
- return await new Promise((resolve) => safeSetTimeout(async () => {
562
- resolve(await benchmark.task.run());
563
- }));
564
- })).then((tasks) => {
565
- suite.result.duration = performance.now() - start;
566
- suite.result.state = "pass";
567
- tasks.sort((a, b) => a.result.mean - b.result.mean).forEach((cycle, idx) => {
568
- const benchmark = benchmarkMap[cycle.name || ""];
569
- benchmark.result.state = "pass";
570
- if (benchmark) {
571
- const result = benchmark.result.benchmark;
572
- result.rank = Number(idx) + 1;
573
- updateTask(benchmark);
574
- }
575
- });
576
- updateTask(suite);
577
- defer.resolve(null);
578
- });
579
- await defer;
580
- }
581
- }
582
- async function runSuiteChild(c) {
583
- if (c.type === "test")
584
- return runTest(c);
585
- else if (c.type === "suite")
586
- return runSuite(c);
587
- }
588
- async function runSuites(suites) {
589
- for (const suite of suites)
590
- await runSuite(suite);
591
- }
592
- async function runFiles(files, config) {
593
- var _a, _b;
594
- for (const file of files) {
595
- if (!file.tasks.length && !config.passWithNoTests) {
596
- if (!((_b = (_a = file.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.length)) {
597
- const error = processError(new Error(`No test suite found in file ${file.filepath}`));
598
- file.result = {
599
- state: "fail",
600
- error,
601
- errors: [error]
602
- };
603
- }
604
- }
605
- await runSuite(file);
606
- }
607
- }
608
- async function startTestsBrowser(paths, config) {
609
- if (isNode) {
610
- rpc().onPathsCollected(paths);
611
- } else {
612
- const files = await collectTests(paths, config);
613
- await rpc().onCollected(files);
614
- await runSuites(files);
615
- await sendTasksUpdate();
616
- }
617
- }
618
- async function startTestsNode(paths, config) {
619
- const files = await collectTests(paths, config);
620
- rpc().onCollected(files);
621
- const { getSnapshotClient: getSnapshotClient2 } = await import('./chunk-runtime-chain.2da9e75c.js').then(function (n) { return n.u; });
622
- getSnapshotClient2().clear();
623
- await runFiles(files, config);
624
- const coverage = await takeCoverageInsideWorker(config.coverage);
625
- rpc().onAfterSuiteRun({ coverage });
626
- await getSnapshotClient2().saveCurrent();
627
- await sendTasksUpdate();
628
- }
629
- async function startTests(paths, config) {
630
- if (config.browser)
631
- return startTestsBrowser(paths, config);
632
- else
633
- return startTestsNode(paths, config);
634
- }
635
- function clearModuleMocks() {
636
- const { clearMocks, mockReset, restoreMocks, unstubEnvs, unstubGlobals } = getWorkerState().config;
637
- if (restoreMocks)
638
- vi.restoreAllMocks();
639
- else if (mockReset)
640
- vi.resetAllMocks();
641
- else if (clearMocks)
642
- vi.clearAllMocks();
643
- if (unstubEnvs)
644
- vi.unstubAllEnvs();
645
- if (unstubGlobals)
646
- vi.unstubAllGlobals();
647
- }
648
-
649
- export { setupGlobalEnv as a, startTests as s, withEnv as w };