vitest 4.0.0-beta.8 → 4.0.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 (85) hide show
  1. package/LICENSE.md +86 -102
  2. package/browser/context.d.ts +7 -0
  3. package/browser/context.js +20 -0
  4. package/dist/browser.d.ts +26 -9
  5. package/dist/browser.js +17 -7
  6. package/dist/chunks/base.CtHM3ryk.js +128 -0
  7. package/dist/chunks/{benchmark.UW6Ezvxy.js → benchmark.DHKMYAts.js} +2 -2
  8. package/dist/chunks/{browser.d.DOMmqJQx.d.ts → browser.d.B9iJzZyn.d.ts} +3 -3
  9. package/dist/chunks/{cac.By1HvRIk.js → cac.B99MQg-w.js} +47 -91
  10. package/dist/chunks/{cli-api.C-JHgQgp.js → cli-api.PwHwIMss.js} +1544 -310
  11. package/dist/chunks/{config.d._GBBbReY.d.ts → config.d.u2CUDWwS.d.ts} +6 -19
  12. package/dist/chunks/{console.B0quX7yH.js → console.CTJL2nuH.js} +4 -6
  13. package/dist/chunks/{coverage.DarITf6U.js → coverage.FU3w4IrQ.js} +128 -1142
  14. package/dist/chunks/{creator.KEg6n5IC.js → creator.DucAaYBz.js} +10 -37
  15. package/dist/chunks/{defaults.CXFFjsi8.js → defaults.BOqNVLsY.js} +0 -1
  16. package/dist/chunks/environment.d.CrsxCzP1.d.ts +29 -0
  17. package/dist/chunks/evaluatedModules.Dg1zASAC.js +17 -0
  18. package/dist/chunks/{global.d.K6uBQHzY.d.ts → global.d.BgJSTpgQ.d.ts} +2 -17
  19. package/dist/chunks/{globals.lgsmH00r.js → globals.BGT_RUsD.js} +12 -9
  20. package/dist/chunks/{index.BuwjkI-q.js → index.BdSLhLDZ.js} +3 -3
  21. package/dist/chunks/{index.DfviD7lX.js → index.CbWINfS7.js} +49 -21
  22. package/dist/chunks/{index.AzwzFtyi.js → index.CcRZ6fUh.js} +1493 -114
  23. package/dist/chunks/{index.X0nbfr6-.js → index.Dc3xnDvT.js} +48 -289
  24. package/dist/chunks/{index.AR8aAkCC.js → index.RwjEGCQ0.js} +7 -8
  25. package/dist/chunks/init-forks.DSafeltJ.js +54 -0
  26. package/dist/chunks/init-threads.SUtZ-067.js +17 -0
  27. package/dist/chunks/init.B2EESLQM.js +213 -0
  28. package/dist/chunks/{inspector.CvQD-Nie.js → inspector.DLZxSeU3.js} +2 -6
  29. package/dist/chunks/{moduleRunner.d.CX4DuqOx.d.ts → moduleRunner.d.YtNsMIoJ.d.ts} +12 -14
  30. package/dist/chunks/{node.BOqcT2jW.js → node.BwAWWjHZ.js} +3 -4
  31. package/dist/chunks/{plugin.d.CHe6slQs.d.ts → plugin.d.DQU1R5px.d.ts} +1 -1
  32. package/dist/chunks/{reporters.d.37tJQ2uV.d.ts → reporters.d.BMKt7f6I.d.ts} +1066 -1030
  33. package/dist/chunks/{index.CsFXYRkW.js → resolveSnapshotEnvironment.DJJKMKxb.js} +18 -24
  34. package/dist/chunks/{rpc.RpPylpp0.js → rpc.cD77ENhU.js} +13 -14
  35. package/dist/chunks/{setup-common.hLGRxhC8.js → setup-common.DR1sucx6.js} +8 -8
  36. package/dist/chunks/{startModuleRunner.C8TW8zTN.js → startModuleRunner.C2tTvmF9.js} +131 -110
  37. package/dist/chunks/test.C3RPt8JR.js +214 -0
  38. package/dist/chunks/{utils.C7__0Iv5.js → utils.CG9h5ccR.js} +3 -15
  39. package/dist/chunks/{vi.BfdOiD4j.js → vi.BZvkKVkM.js} +73 -176
  40. package/dist/chunks/{vm.BHBje7cC.js → vm.DBeOXrP9.js} +29 -33
  41. package/dist/chunks/{worker.d.DYlqbejz.d.ts → worker.d.BFk-vvBU.d.ts} +42 -6
  42. package/dist/cli.js +12 -11
  43. package/dist/config.cjs +0 -1
  44. package/dist/config.d.ts +12 -14
  45. package/dist/config.js +1 -1
  46. package/dist/coverage.d.ts +8 -7
  47. package/dist/coverage.js +3 -14
  48. package/dist/environments.d.ts +3 -6
  49. package/dist/environments.js +1 -1
  50. package/dist/index.d.ts +24 -30
  51. package/dist/index.js +12 -11
  52. package/dist/module-evaluator.d.ts +6 -4
  53. package/dist/module-evaluator.js +14 -16
  54. package/dist/module-runner.js +5 -5
  55. package/dist/node.d.ts +83 -27
  56. package/dist/node.js +23 -20
  57. package/dist/reporters.d.ts +11 -10
  58. package/dist/reporters.js +12 -11
  59. package/dist/runners.d.ts +1 -1
  60. package/dist/runners.js +14 -216
  61. package/dist/snapshot.js +3 -3
  62. package/dist/suite.js +4 -3
  63. package/dist/worker.d.ts +26 -0
  64. package/dist/worker.js +45 -166
  65. package/dist/workers/forks.js +41 -35
  66. package/dist/workers/runVmTests.js +25 -22
  67. package/dist/workers/threads.js +41 -23
  68. package/dist/workers/vmForks.js +26 -39
  69. package/dist/workers/vmThreads.js +26 -29
  70. package/package.json +48 -35
  71. package/worker.d.ts +1 -0
  72. package/browser.d.ts +0 -1
  73. package/dist/chunks/base.BXI97p6t.js +0 -39
  74. package/dist/chunks/environment.d.2fYMoz3o.d.ts +0 -66
  75. package/dist/chunks/moduleTransport.I-bgQy0S.js +0 -19
  76. package/dist/chunks/resolver.Bx6lE0iq.js +0 -119
  77. package/dist/chunks/runBaseTests.D6sfuWBM.js +0 -99
  78. package/dist/chunks/typechecker.DSo_maXz.js +0 -762
  79. package/dist/chunks/utils.C2YI6McM.js +0 -52
  80. package/dist/chunks/worker.d.BKu8cnnX.d.ts +0 -8
  81. package/dist/workers.d.ts +0 -38
  82. package/dist/workers.js +0 -31
  83. package/execute.d.ts +0 -1
  84. package/utils.d.ts +0 -1
  85. package/workers.d.ts +0 -1
@@ -0,0 +1,214 @@
1
+ import { updateTask } from '@vitest/runner';
2
+ import { createDefer } from '@vitest/utils/helpers';
3
+ import { getSafeTimers } from '@vitest/utils/timers';
4
+ import { a as getBenchOptions, g as getBenchFn } from './benchmark.DHKMYAts.js';
5
+ import { g as getWorkerState } from './utils.CG9h5ccR.js';
6
+ import { setState, GLOBAL_EXPECT, getState } from '@vitest/expect';
7
+ import { getTests, getNames, getTestName } from '@vitest/runner/utils';
8
+ import { processError } from '@vitest/utils/error';
9
+ import { normalize } from 'pathe';
10
+ import { a as getSnapshotClient, i as inject, c as createExpect, v as vi } from './vi.BZvkKVkM.js';
11
+ import { r as rpc } from './rpc.cD77ENhU.js';
12
+
13
+ function createBenchmarkResult(name) {
14
+ return {
15
+ name,
16
+ rank: 0,
17
+ rme: 0,
18
+ samples: []
19
+ };
20
+ }
21
+ const benchmarkTasks = /* @__PURE__ */ new WeakMap();
22
+ async function runBenchmarkSuite(suite, runner) {
23
+ const { Task, Bench } = await runner.importTinybench(), start = performance.now(), benchmarkGroup = [], benchmarkSuiteGroup = [];
24
+ for (const task of suite.tasks) {
25
+ if (task.mode !== "run" && task.mode !== "queued") continue;
26
+ if (task.meta?.benchmark) benchmarkGroup.push(task);
27
+ else if (task.type === "suite") benchmarkSuiteGroup.push(task);
28
+ }
29
+ // run sub suites sequentially
30
+ for (const subSuite of benchmarkSuiteGroup) await runBenchmarkSuite(subSuite, runner);
31
+ if (benchmarkGroup.length) {
32
+ const defer = createDefer();
33
+ suite.result = {
34
+ state: "run",
35
+ startTime: start,
36
+ benchmark: createBenchmarkResult(suite.name)
37
+ }, updateTask$1("suite-prepare", suite);
38
+ const addBenchTaskListener = (task, benchmark) => {
39
+ task.addEventListener("complete", (e) => {
40
+ const taskRes = e.task.result, result = benchmark.result.benchmark;
41
+ benchmark.result.state = "pass", Object.assign(result, taskRes);
42
+ // compute extra stats and free raw samples as early as possible
43
+ const samples = result.samples;
44
+ if (result.sampleCount = samples.length, result.median = samples.length % 2 ? samples[Math.floor(samples.length / 2)] : (samples[samples.length / 2] + samples[samples.length / 2 - 1]) / 2, !runner.config.benchmark?.includeSamples) result.samples.length = 0;
45
+ updateTask$1("test-finished", benchmark);
46
+ }, { once: true }), task.addEventListener("error", (e) => {
47
+ const task = e.task;
48
+ defer.reject(benchmark ? task.result.error : e);
49
+ }, { once: true });
50
+ };
51
+ benchmarkGroup.forEach((benchmark) => {
52
+ const options = getBenchOptions(benchmark), benchmarkInstance = new Bench(options), benchmarkFn = getBenchFn(benchmark);
53
+ benchmark.result = {
54
+ state: "run",
55
+ startTime: start,
56
+ benchmark: createBenchmarkResult(benchmark.name)
57
+ };
58
+ const task = new Task(benchmarkInstance, benchmark.name, benchmarkFn);
59
+ benchmarkTasks.set(benchmark, task), addBenchTaskListener(task, benchmark);
60
+ });
61
+ const { setTimeout } = getSafeTimers(), tasks = [];
62
+ for (const benchmark of benchmarkGroup) {
63
+ const task = benchmarkTasks.get(benchmark);
64
+ updateTask$1("test-prepare", benchmark), await task.warmup(), tasks.push([await new Promise((resolve) => setTimeout(async () => {
65
+ resolve(await task.run());
66
+ })), benchmark]);
67
+ }
68
+ suite.result.duration = performance.now() - start, suite.result.state = "pass", updateTask$1("suite-finished", suite), defer.resolve(null), await defer;
69
+ }
70
+ function updateTask$1(event, task) {
71
+ updateTask(event, task, runner);
72
+ }
73
+ }
74
+ class NodeBenchmarkRunner {
75
+ moduleRunner;
76
+ constructor(config) {
77
+ this.config = config;
78
+ }
79
+ async importTinybench() {
80
+ return await import('tinybench');
81
+ }
82
+ importFile(filepath, source) {
83
+ if (source === "setup") {
84
+ const moduleNode = getWorkerState().evaluatedModules.getModuleById(filepath);
85
+ if (moduleNode) getWorkerState().evaluatedModules.invalidateModule(moduleNode);
86
+ }
87
+ return this.moduleRunner.import(filepath);
88
+ }
89
+ async runSuite(suite) {
90
+ await runBenchmarkSuite(suite, this);
91
+ }
92
+ async runTask() {
93
+ throw new Error("`test()` and `it()` is only available in test mode.");
94
+ }
95
+ }
96
+
97
+ // worker context is shared between all tests
98
+ const workerContext = Object.create(null);
99
+ class VitestTestRunner {
100
+ snapshotClient = getSnapshotClient();
101
+ workerState = getWorkerState();
102
+ moduleRunner;
103
+ cancelRun = false;
104
+ assertionsErrors = /* @__PURE__ */ new WeakMap();
105
+ pool = this.workerState.ctx.pool;
106
+ constructor(config) {
107
+ this.config = config;
108
+ }
109
+ importFile(filepath, source) {
110
+ if (source === "setup") {
111
+ const moduleNode = this.workerState.evaluatedModules.getModuleById(filepath);
112
+ if (moduleNode) this.workerState.evaluatedModules.invalidateModule(moduleNode);
113
+ }
114
+ return this.moduleRunner.import(filepath);
115
+ }
116
+ onCollectStart(file) {
117
+ this.workerState.current = file;
118
+ }
119
+ onCleanupWorkerContext(listener) {
120
+ this.workerState.onCleanup(listener);
121
+ }
122
+ onAfterRunFiles() {
123
+ this.snapshotClient.clear(), this.workerState.current = void 0;
124
+ }
125
+ getWorkerContext() {
126
+ return workerContext;
127
+ }
128
+ async onAfterRunSuite(suite) {
129
+ if (this.config.logHeapUsage && typeof process !== "undefined") suite.result.heap = process.memoryUsage().heapUsed;
130
+ if (suite.mode !== "skip" && "filepath" in suite) {
131
+ // mark snapshots in skipped tests as not obsolete
132
+ for (const test of getTests(suite)) if (test.mode === "skip") {
133
+ const name = getNames(test).slice(1).join(" > ");
134
+ this.snapshotClient.skipTest(suite.file.filepath, name);
135
+ }
136
+ const result = await this.snapshotClient.finish(suite.file.filepath);
137
+ if (this.workerState.config.snapshotOptions.updateSnapshot === "none" && result.unchecked) {
138
+ let message = `Obsolete snapshots found when no snapshot update is expected.\n`;
139
+ for (const key of result.uncheckedKeys) message += `· ${key}\n`;
140
+ suite.result.errors ??= [], suite.result.errors.push(processError(new Error(message))), suite.result.state = "fail";
141
+ }
142
+ await rpc().snapshotSaved(result);
143
+ }
144
+ this.workerState.current = suite.suite || suite.file;
145
+ }
146
+ onAfterRunTask(test) {
147
+ if (this.config.logHeapUsage && typeof process !== "undefined") test.result.heap = process.memoryUsage().heapUsed;
148
+ this.workerState.current = test.suite || test.file;
149
+ }
150
+ cancel(_reason) {
151
+ this.cancelRun = true;
152
+ }
153
+ injectValue(key) {
154
+ // inject has a very limiting type controlled by ProvidedContext
155
+ // some tests override it which causes the build to fail
156
+ return inject(key);
157
+ }
158
+ async onBeforeRunTask(test) {
159
+ if (this.cancelRun) test.mode = "skip";
160
+ test.mode !== "run" && test.mode !== "queued" || (this.workerState.current = test);
161
+ }
162
+ async onBeforeRunSuite(suite) {
163
+ if (this.cancelRun) suite.mode = "skip";
164
+ // initialize snapshot state before running file suite
165
+ if (suite.mode !== "skip" && "filepath" in suite) await this.snapshotClient.setup(suite.file.filepath, this.workerState.config.snapshotOptions);
166
+ this.workerState.current = suite;
167
+ }
168
+ onBeforeTryTask(test) {
169
+ clearModuleMocks(this.config), this.snapshotClient.clearTest(test.file.filepath, test.id), setState({
170
+ assertionCalls: 0,
171
+ isExpectingAssertions: false,
172
+ isExpectingAssertionsError: null,
173
+ expectedAssertionsNumber: null,
174
+ expectedAssertionsNumberErrorGen: null,
175
+ currentTestName: getTestName(test),
176
+ snapshotState: this.snapshotClient.getSnapshotState(test.file.filepath)
177
+ }, globalThis[GLOBAL_EXPECT]);
178
+ }
179
+ onAfterTryTask(test) {
180
+ const { assertionCalls, expectedAssertionsNumber, expectedAssertionsNumberErrorGen, isExpectingAssertions, isExpectingAssertionsError } = test.context._local ? test.context.expect.getState() : getState(globalThis[GLOBAL_EXPECT]);
181
+ if (expectedAssertionsNumber !== null && assertionCalls !== expectedAssertionsNumber) throw expectedAssertionsNumberErrorGen();
182
+ if (isExpectingAssertions === true && assertionCalls === 0) throw isExpectingAssertionsError;
183
+ if (this.config.expect.requireAssertions && assertionCalls === 0) throw this.assertionsErrors.get(test);
184
+ }
185
+ extendTaskContext(context) {
186
+ // create error during the test initialization so we have a nice stack trace
187
+ if (this.config.expect.requireAssertions) this.assertionsErrors.set(context.task, /* @__PURE__ */ new Error("expected any number of assertion, but got none"));
188
+ let _expect;
189
+ return Object.defineProperty(context, "expect", { get() {
190
+ if (!_expect) _expect = createExpect(context.task);
191
+ return _expect;
192
+ } }), Object.defineProperty(context, "_local", { get() {
193
+ return _expect != null;
194
+ } }), context;
195
+ }
196
+ getImportDurations() {
197
+ const entries = [...this.workerState.moduleExecutionInfo?.entries() ?? []];
198
+ return Object.fromEntries(entries.map(([filepath, { duration, selfTime }]) => [normalize(filepath), {
199
+ selfTime,
200
+ totalTime: duration
201
+ }]));
202
+ }
203
+ }
204
+ function clearModuleMocks(config) {
205
+ const { clearMocks, mockReset, restoreMocks, unstubEnvs, unstubGlobals } = config;
206
+ // since each function calls another, we can just call one
207
+ if (restoreMocks) vi.restoreAllMocks();
208
+ else if (mockReset) vi.resetAllMocks();
209
+ else if (clearMocks) vi.clearAllMocks();
210
+ if (unstubEnvs) vi.unstubAllEnvs();
211
+ if (unstubGlobals) vi.unstubAllGlobals();
212
+ }
213
+
214
+ export { NodeBenchmarkRunner as N, VitestTestRunner as V };
@@ -1,13 +1,10 @@
1
- import { getSafeTimers } from '@vitest/utils';
1
+ import { getSafeTimers } from '@vitest/utils/timers';
2
2
 
3
3
  const NAME_WORKER_STATE = "__vitest_worker__";
4
4
  function getWorkerState() {
5
5
  // @ts-expect-error untyped global
6
6
  const workerState = globalThis[NAME_WORKER_STATE];
7
- if (!workerState) {
8
- const errorMsg = "Vitest failed to access its internal state.\n\nOne of the following is possible:\n- \"vitest\" is imported directly without running \"vitest\" command\n- \"vitest\" is imported inside \"globalSetup\" (to fix this, use \"setupFiles\" instead, because \"globalSetup\" runs in a different context)\n- \"vitest\" is imported inside Vite / Vitest config file\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n";
9
- throw new Error(errorMsg);
10
- }
7
+ if (!workerState) throw new Error("Vitest failed to access its internal state.\n\nOne of the following is possible:\n- \"vitest\" is imported directly without running \"vitest\" command\n- \"vitest\" is imported inside \"globalSetup\" (to fix this, use \"setupFiles\" instead, because \"globalSetup\" runs in a different context)\n- \"vitest\" is imported inside Vite / Vitest config file\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n");
11
8
  return workerState;
12
9
  }
13
10
  function provideWorkerState(context, state) {
@@ -18,18 +15,9 @@ function provideWorkerState(context, state) {
18
15
  enumerable: false
19
16
  }), state;
20
17
  }
21
- function getCurrentEnvironment() {
22
- const state = getWorkerState();
23
- return state?.environment.name;
24
- }
25
18
  function isChildProcess() {
26
19
  return typeof process !== "undefined" && !!process.send;
27
20
  }
28
- function setProcessTitle(title) {
29
- try {
30
- process.title = `node (${title})`;
31
- } catch {}
32
- }
33
21
  function resetModules(modules, resetMocks = false) {
34
22
  const skipPaths = [
35
23
  /\/vitest\/dist\//,
@@ -52,4 +40,4 @@ async function waitForImportsToResolve() {
52
40
  !promises.length && !resolvingCount || (await Promise.allSettled(promises), await waitForImportsToResolve());
53
41
  }
54
42
 
55
- export { getCurrentEnvironment as a, getWorkerState as g, isChildProcess as i, provideWorkerState as p, resetModules as r, setProcessTitle as s, waitForImportsToResolve as w };
43
+ export { getWorkerState as g, isChildProcess as i, provideWorkerState as p, resetModules as r, waitForImportsToResolve as w };