vitest 4.0.0-beta.7 → 4.0.0-beta.9

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 (56) hide show
  1. package/dist/browser.d.ts +5 -5
  2. package/dist/browser.js +4 -4
  3. package/dist/chunks/{runBaseTests.D6sfuWBM.js → base.CA5N8Af0.js} +55 -26
  4. package/dist/chunks/{benchmark.UW6Ezvxy.js → benchmark.CJUa-Hsa.js} +1 -1
  5. package/dist/chunks/{browser.d.DOMmqJQx.d.ts → browser.d.DtfyY9yS.d.ts} +1 -1
  6. package/dist/chunks/{cac.Dsn7ixFt.js → cac.Dt7e1TIu.js} +6 -25
  7. package/dist/chunks/{cli-api.DfGJyldU.js → cli-api.eAzsLIxz.js} +88 -209
  8. package/dist/chunks/{config.d._GBBbReY.d.ts → config.d.DacWrqWe.d.ts} +1 -0
  9. package/dist/chunks/{console.B0quX7yH.js → console.7h5kHUIf.js} +1 -1
  10. package/dist/chunks/{coverage.Dvxug1RM.js → coverage.CDRAMTt7.js} +25 -56
  11. package/dist/chunks/{globals.lgsmH00r.js → globals.CJrTTbxC.js} +5 -6
  12. package/dist/chunks/{index.C3EbxYwt.js → index.BIP7prJq.js} +7 -3
  13. package/dist/chunks/{index.D2B6d2vv.js → index.BjKEiSn0.js} +1 -1
  14. package/dist/chunks/{index.AR8aAkCC.js → index.C832ioot.js} +5 -6
  15. package/dist/chunks/{moduleRunner.d.CX4DuqOx.d.ts → moduleRunner.d.DxTLreRD.d.ts} +4 -1
  16. package/dist/chunks/{node.BOqcT2jW.js → node.CyipiPvJ.js} +1 -1
  17. package/dist/chunks/{plugin.d.vcD4xbMS.d.ts → plugin.d.CIk0YiKb.d.ts} +1 -1
  18. package/dist/chunks/{reporters.d.BC86JJdB.d.ts → reporters.d.DmP-iHLr.d.ts} +451 -561
  19. package/dist/chunks/{index.CsFXYRkW.js → resolveSnapshotEnvironment.Bvv2zr69.js} +16 -21
  20. package/dist/chunks/{rpc.RpPylpp0.js → rpc.BKr6mtxz.js} +1 -1
  21. package/dist/chunks/{setup-common.hLGRxhC8.js → setup-common.B7I37Tji.js} +4 -4
  22. package/dist/chunks/{startModuleRunner.C8TW8zTN.js → startModuleRunner.BDRvKSdz.js} +7 -2
  23. package/dist/chunks/test.BAlBebnP.js +214 -0
  24. package/dist/chunks/{typechecker.DSo_maXz.js → typechecker.DB-fIMaH.js} +44 -1
  25. package/dist/chunks/{utils.C7__0Iv5.js → utils.D2R2NiOH.js} +1 -10
  26. package/dist/chunks/{vi.BfdOiD4j.js → vi.BB37KeLx.js} +16 -16
  27. package/dist/chunks/{vm.BHBje7cC.js → vm.CjLTDaST.js} +12 -7
  28. package/dist/chunks/{worker.d.DYlqbejz.d.ts → worker.d.B2r4Ln6p.d.ts} +1 -1
  29. package/dist/chunks/{worker.d.BKu8cnnX.d.ts → worker.d.DJ6qxO2w.d.ts} +1 -1
  30. package/dist/cli.js +3 -3
  31. package/dist/config.d.ts +10 -10
  32. package/dist/coverage.d.ts +8 -8
  33. package/dist/coverage.js +2 -2
  34. package/dist/index.d.ts +11 -12
  35. package/dist/index.js +5 -8
  36. package/dist/module-evaluator.d.ts +4 -3
  37. package/dist/module-evaluator.js +3 -3
  38. package/dist/module-runner.js +2 -2
  39. package/dist/node.d.ts +23 -14
  40. package/dist/node.js +8 -8
  41. package/dist/reporters.d.ts +8 -8
  42. package/dist/reporters.js +3 -3
  43. package/dist/runners.d.ts +1 -1
  44. package/dist/runners.js +11 -215
  45. package/dist/snapshot.js +2 -2
  46. package/dist/suite.js +2 -2
  47. package/dist/worker.js +2 -3
  48. package/dist/workers/forks.js +27 -4
  49. package/dist/workers/runVmTests.js +18 -19
  50. package/dist/workers/threads.js +27 -4
  51. package/dist/workers/vmForks.js +4 -4
  52. package/dist/workers/vmThreads.js +4 -4
  53. package/dist/workers.d.ts +3 -3
  54. package/dist/workers.js +26 -8
  55. package/package.json +10 -14
  56. package/dist/chunks/base.BXI97p6t.js +0 -39
@@ -1,30 +1,15 @@
1
- import * as chai from 'chai';
2
- import { resolve, join } from 'node:path';
3
- import { l as loadDiffConfig, b as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.hLGRxhC8.js';
4
- import { distDir } from '../path.js';
5
- import { r as rpc } from './rpc.RpPylpp0.js';
6
- import { g as getWorkerState } from './utils.C7__0Iv5.js';
1
+ import { chai } from '@vitest/expect';
2
+ import { l as loadDiffConfig, b as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.B7I37Tji.js';
3
+ import { r as rpc } from './rpc.BKr6mtxz.js';
4
+ import { g as getWorkerState } from './utils.D2R2NiOH.js';
5
+ import { V as VitestTestRunner, N as NodeBenchmarkRunner } from './test.BAlBebnP.js';
7
6
 
8
7
  function setupChaiConfig(config) {
9
8
  Object.assign(chai.config, config);
10
9
  }
11
10
 
12
- async function resolveSnapshotEnvironment(config, executor) {
13
- if (!config.snapshotEnvironment) {
14
- const { VitestNodeSnapshotEnvironment } = await import('./node.BOqcT2jW.js');
15
- return new VitestNodeSnapshotEnvironment();
16
- }
17
- const mod = await executor.import(config.snapshotEnvironment);
18
- if (typeof mod.default !== "object" || !mod.default) throw new Error("Snapshot environment module must have a default export object with a shape of `SnapshotEnvironment`");
19
- return mod.default;
20
- }
21
-
22
- const runnersFile = resolve(distDir, "runners.js");
23
11
  async function getTestRunnerConstructor(config, moduleRunner) {
24
- if (!config.runner) {
25
- const { VitestTestRunner, NodeBenchmarkRunner } = await moduleRunner.import(join("/@fs/", runnersFile));
26
- return config.mode === "test" ? VitestTestRunner : NodeBenchmarkRunner;
27
- }
12
+ if (!config.runner) return config.mode === "test" ? VitestTestRunner : NodeBenchmarkRunner;
28
13
  const mod = await moduleRunner.import(config.runner);
29
14
  if (!mod.default && typeof mod.default !== "function") throw new Error(`Runner must export a default function, but got ${typeof mod.default} imported from ${config.runner}`);
30
15
  return mod.default;
@@ -83,4 +68,14 @@ async function resolveTestRunner(config, moduleRunner) {
83
68
  }, testRunner;
84
69
  }
85
70
 
71
+ async function resolveSnapshotEnvironment(config, executor) {
72
+ if (!config.snapshotEnvironment) {
73
+ const { VitestNodeSnapshotEnvironment } = await import('./node.CyipiPvJ.js');
74
+ return new VitestNodeSnapshotEnvironment();
75
+ }
76
+ const mod = await executor.import(config.snapshotEnvironment);
77
+ if (typeof mod.default !== "object" || !mod.default) throw new Error("Snapshot environment module must have a default export object with a shape of `SnapshotEnvironment`");
78
+ return mod.default;
79
+ }
80
+
86
81
  export { resolveSnapshotEnvironment as a, resolveTestRunner as r, setupChaiConfig as s };
@@ -1,6 +1,6 @@
1
1
  import { getSafeTimers } from '@vitest/utils';
2
2
  import { c as createBirpc } from './index.Bgo3tNWt.js';
3
- import { g as getWorkerState } from './utils.C7__0Iv5.js';
3
+ import { g as getWorkerState } from './utils.D2R2NiOH.js';
4
4
 
5
5
  const { get } = Reflect;
6
6
  function withSafeTimers(fn) {
@@ -1,7 +1,7 @@
1
1
  import { r as resolveCoverageProviderModule } from './coverage.D_JHT54q.js';
2
2
  import { addSerializer } from '@vitest/snapshot';
3
3
  import { setSafeTimers } from '@vitest/utils';
4
- import { g as getWorkerState } from './utils.C7__0Iv5.js';
4
+ import { g as getWorkerState } from './utils.D2R2NiOH.js';
5
5
 
6
6
  async function startCoverageInsideWorker(options, loader, runtimeOptions) {
7
7
  const coverageModule = await resolveCoverageProviderModule(options, loader);
@@ -18,10 +18,10 @@ async function stopCoverageInsideWorker(options, loader, runtimeOptions) {
18
18
 
19
19
  let globalSetup = false;
20
20
  async function setupCommonEnv(config) {
21
- if (setupDefines(config.defines), setupEnv(config.env), !globalSetup && (globalSetup = true, setSafeTimers(), config.globals)) (await import('./globals.lgsmH00r.js')).registerApiGlobally();
21
+ if (setupDefines(config), setupEnv(config.env), !globalSetup && (globalSetup = true, setSafeTimers(), config.globals)) (await import('./globals.CJrTTbxC.js')).registerApiGlobally();
22
22
  }
23
- function setupDefines(defines) {
24
- for (const key in defines) globalThis[key] = defines[key];
23
+ function setupDefines(config) {
24
+ for (const key in config.defines) globalThis[key] = config.defines[key];
25
25
  }
26
26
  function setupEnv(env) {
27
27
  const state = getWorkerState(), { PROD, DEV,...restEnvs } = env;
@@ -233,6 +233,7 @@ class VitestMocker {
233
233
  Array,
234
234
  Map
235
235
  };
236
+ if (options.spyModule) this.spyModule = options.spyModule;
236
237
  const Symbol = this.primitives.Symbol;
237
238
  this.filterPublicKeys = [
238
239
  "__esModule",
@@ -500,6 +501,7 @@ class VitestModuleRunner extends ModuleRunner {
500
501
  evaluatedModules,
501
502
  sourcemapInterceptor: "prepareStackTrace"
502
503
  }, options.evaluator), this.options = options, this.moduleExecutionInfo = options.getWorkerState().moduleExecutionInfo, this.mocker = options.mocker || new VitestMocker(this, {
504
+ spyModule: options.spyModule,
503
505
  context: options.vm?.context,
504
506
  resolveId: options.transport.resolveId,
505
507
  get root() {
@@ -561,7 +563,7 @@ class VitestModuleRunner extends ModuleRunner {
561
563
  const { readFileSync } = fs, browserExternalId = "__vite-browser-external", browserExternalLength = 24;
562
564
  const VITEST_VM_CONTEXT_SYMBOL = "__vitest_vm_context__";
563
565
  const cwd = process.cwd(), isWindows = process.platform === "win32";
564
- async function startVitestModuleRunner(options) {
566
+ function startVitestModuleRunner(options) {
565
567
  const state = () => globalThis.__vitest_worker__ || options.state, rpc = () => state().rpc;
566
568
  process.exit = (code = process.exitCode || 0) => {
567
569
  throw new Error(`process.exit unexpectedly called with "${code}"`);
@@ -581,6 +583,7 @@ async function startVitestModuleRunner(options) {
581
583
  },
582
584
  getCurrentTestFilepath: () => state().filepath
583
585
  }), moduleRunner = new VitestModuleRunner({
586
+ spyModule: options.spyModule,
584
587
  evaluatedModules: options.evaluatedModules,
585
588
  evaluator,
586
589
  mocker: options.mocker,
@@ -644,7 +647,9 @@ async function startVitestModuleRunner(options) {
644
647
  getWorkerState: state,
645
648
  vm
646
649
  });
647
- return await moduleRunner.import("/@vite/env"), await moduleRunner.mocker.initializeSpyModule(), moduleRunner;
650
+ // await moduleRunner.import('/@vite/env')
651
+ // await moduleRunner.mocker.initializeSpyModule()
652
+ return moduleRunner;
648
653
  }
649
654
  function toBuiltin(id) {
650
655
  if (id.startsWith(browserExternalId)) id = id.slice(browserExternalLength);
@@ -0,0 +1,214 @@
1
+ import { updateTask } from '@vitest/runner';
2
+ import { createDefer, getSafeTimers } from '@vitest/utils';
3
+ import { a as getBenchOptions, g as getBenchFn } from './benchmark.CJUa-Hsa.js';
4
+ import { g as getWorkerState } from './utils.D2R2NiOH.js';
5
+ import { setState, GLOBAL_EXPECT, getState } from '@vitest/expect';
6
+ import { getTests, getNames, getTestName } from '@vitest/runner/utils';
7
+ import { processError } from '@vitest/utils/error';
8
+ import { normalize } from 'pathe';
9
+ import { a as getSnapshotClient, i as inject, c as createExpect, v as vi } from './vi.BB37KeLx.js';
10
+ import { r as rpc } from './rpc.BKr6mtxz.js';
11
+
12
+ function createBenchmarkResult(name) {
13
+ return {
14
+ name,
15
+ rank: 0,
16
+ rme: 0,
17
+ samples: []
18
+ };
19
+ }
20
+ const benchmarkTasks = /* @__PURE__ */ new WeakMap();
21
+ async function runBenchmarkSuite(suite, runner) {
22
+ const { Task, Bench } = await runner.importTinybench(), start = performance.now(), benchmarkGroup = [], benchmarkSuiteGroup = [];
23
+ for (const task of suite.tasks) {
24
+ if (task.mode !== "run" && task.mode !== "queued") continue;
25
+ if (task.meta?.benchmark) benchmarkGroup.push(task);
26
+ else if (task.type === "suite") benchmarkSuiteGroup.push(task);
27
+ }
28
+ // run sub suites sequentially
29
+ for (const subSuite of benchmarkSuiteGroup) await runBenchmarkSuite(subSuite, runner);
30
+ if (benchmarkGroup.length) {
31
+ const defer = createDefer();
32
+ suite.result = {
33
+ state: "run",
34
+ startTime: start,
35
+ benchmark: createBenchmarkResult(suite.name)
36
+ }, updateTask$1("suite-prepare", suite);
37
+ const addBenchTaskListener = (task, benchmark) => {
38
+ task.addEventListener("complete", (e) => {
39
+ const task = e.task, taskRes = task.result, result = benchmark.result.benchmark;
40
+ benchmark.result.state = "pass", Object.assign(result, taskRes);
41
+ // compute extra stats and free raw samples as early as possible
42
+ const samples = result.samples;
43
+ 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;
44
+ updateTask$1("test-finished", benchmark);
45
+ }, { once: true }), task.addEventListener("error", (e) => {
46
+ const task = e.task;
47
+ defer.reject(benchmark ? task.result.error : e);
48
+ }, { once: true });
49
+ };
50
+ benchmarkGroup.forEach((benchmark) => {
51
+ const options = getBenchOptions(benchmark), benchmarkInstance = new Bench(options), benchmarkFn = getBenchFn(benchmark);
52
+ benchmark.result = {
53
+ state: "run",
54
+ startTime: start,
55
+ benchmark: createBenchmarkResult(benchmark.name)
56
+ };
57
+ const task = new Task(benchmarkInstance, benchmark.name, benchmarkFn);
58
+ benchmarkTasks.set(benchmark, task), addBenchTaskListener(task, benchmark);
59
+ });
60
+ const { setTimeout } = getSafeTimers(), tasks = [];
61
+ for (const benchmark of benchmarkGroup) {
62
+ const task = benchmarkTasks.get(benchmark);
63
+ updateTask$1("test-prepare", benchmark), await task.warmup(), tasks.push([await new Promise((resolve) => setTimeout(async () => {
64
+ resolve(await task.run());
65
+ })), benchmark]);
66
+ }
67
+ suite.result.duration = performance.now() - start, suite.result.state = "pass", updateTask$1("suite-finished", suite), defer.resolve(null), await defer;
68
+ }
69
+ function updateTask$1(event, task) {
70
+ updateTask(event, task, runner);
71
+ }
72
+ }
73
+ class NodeBenchmarkRunner {
74
+ moduleRunner;
75
+ constructor(config) {
76
+ this.config = config;
77
+ }
78
+ async importTinybench() {
79
+ return await import('tinybench');
80
+ }
81
+ importFile(filepath, source) {
82
+ if (source === "setup") {
83
+ const moduleNode = getWorkerState().evaluatedModules.getModuleById(filepath);
84
+ if (moduleNode) getWorkerState().evaluatedModules.invalidateModule(moduleNode);
85
+ }
86
+ return this.moduleRunner.import(filepath);
87
+ }
88
+ async runSuite(suite) {
89
+ await runBenchmarkSuite(suite, this);
90
+ }
91
+ async runTask() {
92
+ throw new Error("`test()` and `it()` is only available in test mode.");
93
+ }
94
+ }
95
+
96
+ // import type { VitestExecutor } from '../execute'
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 };
@@ -30,6 +30,49 @@ function wrapSerializableConfig(config) {
30
30
  defines
31
31
  };
32
32
  }
33
+ function createDefinesScript(define) {
34
+ if (!define) return "";
35
+ const serializedDefine = serializeDefine(define);
36
+ return serializedDefine === "{}" ? "" : `
37
+ const defines = ${serializeDefine(define)}
38
+ Object.keys(defines).forEach((key) => {
39
+ const segments = key.split('.')
40
+ let target = globalThis
41
+ for (let i = 0; i < segments.length; i++) {
42
+ const segment = segments[i]
43
+ if (i === segments.length - 1) {
44
+ target[segment] = defines[key]
45
+ } else {
46
+ target = target[segment] || (target[segment] = {})
47
+ }
48
+ }
49
+ })
50
+ `;
51
+ }
52
+ /**
53
+ * Like `JSON.stringify` but keeps raw string values as a literal
54
+ * in the generated code. For example: `"window"` would refer to
55
+ * the global `window` object directly.
56
+ */
57
+ function serializeDefine(define) {
58
+ const userDefine = {};
59
+ for (const key in define) {
60
+ // vitest sets this to avoid vite:client-inject plugin
61
+ if (key === "process.env.NODE_ENV" && define[key] === "process.env.NODE_ENV") continue;
62
+ // import.meta.env.* is handled in `importAnalysis` plugin
63
+ if (!key.startsWith("import.meta.env.")) userDefine[key] = define[key];
64
+ }
65
+ let res = `{`;
66
+ const keys = Object.keys(userDefine).sort();
67
+ for (let i = 0; i < keys.length; i++) {
68
+ const key = keys[i], val = userDefine[key];
69
+ if (res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`, i !== keys.length - 1) res += `, `;
70
+ }
71
+ return `${res}}`;
72
+ }
73
+ function handleDefineValue(value) {
74
+ return typeof value === "undefined" ? "undefined" : typeof value === "string" ? value : JSON.stringify(value);
75
+ }
33
76
 
34
77
  function hasFailedSnapshot(suite) {
35
78
  return getTests(suite).some((s) => {
@@ -759,4 +802,4 @@ function findGeneratedPosition(traceMap, { line, column, source }) {
759
802
  };
760
803
  }
761
804
 
762
- export { TypeCheckError as T, Typechecker as a, ancestor as b, convertTasksToEvents as c, getOutputFile as g, hasFailedSnapshot as h, wrapSerializableConfig as w };
805
+ export { TypeCheckError as T, Typechecker as a, ancestor as b, createDefinesScript as c, convertTasksToEvents as d, getOutputFile as g, hasFailedSnapshot as h, wrapSerializableConfig as w };
@@ -18,18 +18,9 @@ function provideWorkerState(context, state) {
18
18
  enumerable: false
19
19
  }), state;
20
20
  }
21
- function getCurrentEnvironment() {
22
- const state = getWorkerState();
23
- return state?.environment.name;
24
- }
25
21
  function isChildProcess() {
26
22
  return typeof process !== "undefined" && !!process.send;
27
23
  }
28
- function setProcessTitle(title) {
29
- try {
30
- process.title = `node (${title})`;
31
- } catch {}
32
- }
33
24
  function resetModules(modules, resetMocks = false) {
34
25
  const skipPaths = [
35
26
  /\/vitest\/dist\//,
@@ -52,4 +43,4 @@ async function waitForImportsToResolve() {
52
43
  !promises.length && !resolvingCount || (await Promise.allSettled(promises), await waitForImportsToResolve());
53
44
  }
54
45
 
55
- export { getCurrentEnvironment as a, getWorkerState as g, isChildProcess as i, provideWorkerState as p, resetModules as r, setProcessTitle as s, waitForImportsToResolve as w };
46
+ export { getWorkerState as g, isChildProcess as i, provideWorkerState as p, resetModules as r, waitForImportsToResolve as w };
@@ -1,8 +1,7 @@
1
- import { equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, JestAsymmetricMatchers, GLOBAL_EXPECT, ASYMMETRIC_MATCHERS_OBJECT, getState, setState, addCustomEqualityTesters, customMatchers } from '@vitest/expect';
1
+ import { chai as chai$1, equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, JestAsymmetricMatchers, GLOBAL_EXPECT, ASYMMETRIC_MATCHERS_OBJECT, getState, setState, addCustomEqualityTesters, customMatchers } from '@vitest/expect';
2
2
  import { getCurrentTest } from '@vitest/runner';
3
3
  import { getNames, getTestName } from '@vitest/runner/utils';
4
- import * as chai$1 from 'chai';
5
- import { g as getWorkerState, a as getCurrentEnvironment, i as isChildProcess, w as waitForImportsToResolve, r as resetModules } from './utils.C7__0Iv5.js';
4
+ import { g as getWorkerState, i as isChildProcess, w as waitForImportsToResolve, r as resetModules } from './utils.D2R2NiOH.js';
6
5
  import { getSafeTimers, assertTypes, createSimpleStackTrace } from '@vitest/utils';
7
6
  import { g as getDefaultExportFromCjs, c as commonjsGlobal } from './_commonjsHelpers.BFTU3MAI.js';
8
7
  import { stripSnapshotIndentation, addSerializer, SnapshotClient } from '@vitest/snapshot';
@@ -359,7 +358,6 @@ function createExpect(test) {
359
358
  isExpectingAssertionsError: null,
360
359
  expectedAssertionsNumber: null,
361
360
  expectedAssertionsNumberErrorGen: null,
362
- environment: getCurrentEnvironment(),
363
361
  get testPath() {
364
362
  return getWorkerState().filepath;
365
363
  },
@@ -394,6 +392,8 @@ Object.defineProperty(globalThis, GLOBAL_EXPECT, {
394
392
  writable: true,
395
393
  configurable: true
396
394
  });
395
+ const assert = chai$1.assert;
396
+ const should = chai$1.should;
397
397
 
398
398
  /**
399
399
  * Gives access to injected context provided from the main thread.
@@ -3677,11 +3677,11 @@ function waitUntil(callback, options = {}) {
3677
3677
 
3678
3678
  function createVitest() {
3679
3679
  let _config = null;
3680
- const workerState = getWorkerState();
3680
+ const state = () => getWorkerState();
3681
3681
  let _timers;
3682
3682
  const timers = () => _timers ||= new FakeTimers({
3683
3683
  global: globalThis,
3684
- config: workerState.config.fakeTimers
3684
+ config: state().config.fakeTimers
3685
3685
  }), _stubsGlobal = /* @__PURE__ */ new Map(), _stubsEnv = /* @__PURE__ */ new Map(), _envBooleans = [
3686
3686
  "PROD",
3687
3687
  "DEV",
@@ -3689,13 +3689,13 @@ function createVitest() {
3689
3689
  ], utils = {
3690
3690
  useFakeTimers(config) {
3691
3691
  if (isChildProcess()) {
3692
- if (config?.toFake?.includes("nextTick") || workerState.config?.fakeTimers?.toFake?.includes("nextTick")) throw new Error("vi.useFakeTimers({ toFake: [\"nextTick\"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.");
3692
+ if (config?.toFake?.includes("nextTick") || state().config?.fakeTimers?.toFake?.includes("nextTick")) throw new Error("vi.useFakeTimers({ toFake: [\"nextTick\"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.");
3693
3693
  }
3694
3694
  if (config) timers().configure({
3695
- ...workerState.config.fakeTimers,
3695
+ ...state().config.fakeTimers,
3696
3696
  ...config
3697
3697
  });
3698
- else timers().configure(workerState.config.fakeTimers);
3698
+ else timers().configure(state().config.fakeTimers);
3699
3699
  return timers().useFakeTimers(), utils;
3700
3700
  },
3701
3701
  isFakeTimers() {
@@ -3808,7 +3808,7 @@ function createVitest() {
3808
3808
  }), utils;
3809
3809
  },
3810
3810
  stubEnv(name, value) {
3811
- const state = getWorkerState(), env = state.metaEnv;
3811
+ const env = state().metaEnv;
3812
3812
  if (!_stubsEnv.has(name)) _stubsEnv.set(name, env[name]);
3813
3813
  if (_envBooleans.includes(name)) env[name] = value ? "1" : "";
3814
3814
  else if (value === void 0) delete env[name];
@@ -3822,24 +3822,24 @@ function createVitest() {
3822
3822
  }), _stubsGlobal.clear(), utils;
3823
3823
  },
3824
3824
  unstubAllEnvs() {
3825
- const state = getWorkerState(), env = state.metaEnv;
3825
+ const env = state().metaEnv;
3826
3826
  return _stubsEnv.forEach((original, name) => {
3827
3827
  if (original === void 0) delete env[name];
3828
3828
  else env[name] = original;
3829
3829
  }), _stubsEnv.clear(), utils;
3830
3830
  },
3831
3831
  resetModules() {
3832
- return resetModules(workerState.evaluatedModules), utils;
3832
+ return resetModules(state().evaluatedModules), utils;
3833
3833
  },
3834
3834
  async dynamicImportSettled() {
3835
3835
  return waitForImportsToResolve();
3836
3836
  },
3837
3837
  setConfig(config) {
3838
- if (!_config) _config = { ...workerState.config };
3839
- Object.assign(workerState.config, config);
3838
+ if (!_config) _config = { ...state().config };
3839
+ Object.assign(state().config, config);
3840
3840
  },
3841
3841
  resetConfig() {
3842
- if (_config) Object.assign(workerState.config, _config);
3842
+ if (_config) Object.assign(state().config, _config);
3843
3843
  }
3844
3844
  };
3845
3845
  return utils;
@@ -3859,4 +3859,4 @@ function getImporter(name) {
3859
3859
  return stack?.file || "";
3860
3860
  }
3861
3861
 
3862
- export { globalExpect as a, vitest as b, createExpect as c, getSnapshotClient as g, inject as i, vi as v };
3862
+ export { getSnapshotClient as a, assert as b, createExpect as c, vitest as d, globalExpect as g, inject as i, should as s, vi as v };
@@ -1,16 +1,16 @@
1
1
  import { fileURLToPath, pathToFileURL } from 'node:url';
2
- import vm, { isContext } from 'node:vm';
2
+ import vm, { isContext, runInContext } from 'node:vm';
3
3
  import { dirname, basename, extname, normalize, resolve } from 'pathe';
4
4
  import { distDir } from '../path.js';
5
- import { createCustomConsole } from './console.B0quX7yH.js';
5
+ import { createCustomConsole } from './console.7h5kHUIf.js';
6
6
  import fs from 'node:fs';
7
7
  import { createRequire, Module, isBuiltin } from 'node:module';
8
8
  import { CSS_LANGS_RE, KNOWN_ASSET_RE, toArray, isBareImport } from '@vitest/utils';
9
9
  import { f as findNearestPackageData } from './resolver.Bx6lE0iq.js';
10
10
  import { dirname as dirname$1 } from 'node:path';
11
11
  import { getDefaultRequestStubs } from '../module-evaluator.js';
12
- import { s as startVitestModuleRunner, a as VITEST_VM_CONTEXT_SYMBOL } from './startModuleRunner.C8TW8zTN.js';
13
- import { p as provideWorkerState } from './utils.C7__0Iv5.js';
12
+ import { s as startVitestModuleRunner, a as VITEST_VM_CONTEXT_SYMBOL } from './startModuleRunner.BDRvKSdz.js';
13
+ import { p as provideWorkerState } from './utils.D2R2NiOH.js';
14
14
 
15
15
  function interopCommonJsModule(interopDefault, mod) {
16
16
  if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) return {
@@ -611,13 +611,13 @@ async function runVmTests(method, state) {
611
611
  packageCache,
612
612
  transform: rpc.transform,
613
613
  viteClientModule: stubs["/@vite/client"]
614
- }), moduleRunner = await startVitestModuleRunner({
614
+ }), moduleRunner = startVitestModuleRunner({
615
615
  context,
616
616
  evaluatedModules: state.evaluatedModules,
617
617
  state,
618
618
  externalModulesExecutor
619
619
  });
620
- Object.defineProperty(context, VITEST_VM_CONTEXT_SYMBOL, {
620
+ if (Object.defineProperty(context, VITEST_VM_CONTEXT_SYMBOL, {
621
621
  value: {
622
622
  context,
623
623
  externalModulesExecutor
@@ -625,7 +625,12 @@ async function runVmTests(method, state) {
625
625
  configurable: true,
626
626
  enumerable: false,
627
627
  writable: false
628
- }), context.__vitest_mocker__ = moduleRunner.mocker;
628
+ }), context.__vitest_mocker__ = moduleRunner.mocker, ctx.config.serializedDefines) try {
629
+ runInContext(ctx.config.serializedDefines, context, { filename: "virtual:load-defines.js" });
630
+ } catch (error) {
631
+ throw new Error(`Failed to load custom "defines": ${error.message}`);
632
+ }
633
+ await moduleRunner.mocker.initializeSpyModule();
629
634
  const { run } = await moduleRunner.import(entryFile), fileSpecs = ctx.files.map((f) => typeof f === "string" ? {
630
635
  filepath: f,
631
636
  testLocations: void 0
@@ -1,6 +1,6 @@
1
1
  import { CancelReason, File, TestAnnotation, TaskResultPack, TaskEventPack, FileSpecification, Task } from '@vitest/runner';
2
2
  import { FetchFunctionOptions, FetchResult, EvaluatedModules } from 'vite/module-runner';
3
- import { a as SerializedConfig } from './config.d._GBBbReY.js';
3
+ import { a as SerializedConfig } from './config.d.DacWrqWe.js';
4
4
  import { F as FetchCachedFileSystemResult, R as ResolveFunctionResult, U as UserConsoleLog, A as AfterSuiteRunMeta, E as Environment } from './environment.d.2fYMoz3o.js';
5
5
  import { SnapshotResult } from '@vitest/snapshot';
6
6
 
@@ -1,5 +1,5 @@
1
1
  import { MessagePort } from 'node:worker_threads';
2
- import { C as ContextRPC } from './worker.d.DYlqbejz.js';
2
+ import { C as ContextRPC } from './worker.d.B2r4Ln6p.js';
3
3
 
4
4
  interface WorkerContext extends ContextRPC {
5
5
  port: MessagePort;
package/dist/cli.js CHANGED
@@ -1,13 +1,13 @@
1
- import { c as createCLI } from './chunks/cac.Dsn7ixFt.js';
1
+ import { c as createCLI } from './chunks/cac.Dt7e1TIu.js';
2
2
  import '@vitest/utils';
3
3
  import 'events';
4
4
  import 'pathe';
5
5
  import 'tinyrainbow';
6
6
  import './chunks/constants.D_Q9UYh-.js';
7
- import './chunks/index.C3EbxYwt.js';
7
+ import './chunks/index.BIP7prJq.js';
8
8
  import 'node:fs';
9
9
  import 'node:fs/promises';
10
- import './chunks/typechecker.DSo_maXz.js';
10
+ import './chunks/typechecker.DB-fIMaH.js';
11
11
  import 'node:os';
12
12
  import 'node:perf_hooks';
13
13
  import '@vitest/utils/source-map';
package/dist/config.d.ts CHANGED
@@ -1,23 +1,22 @@
1
1
  import { HookHandler, ConfigEnv, UserConfig } from 'vite';
2
2
  export { ConfigEnv, Plugin, UserConfig as ViteUserConfig, mergeConfig } from 'vite';
3
- import { I as InlineConfig, c as CoverageV8Options, R as ResolvedCoverageOptions, U as UserWorkspaceConfig, d as UserProjectConfigFn, e as UserProjectConfigExport } from './chunks/reporters.d.BC86JJdB.js';
4
- export { a as TestProjectConfiguration, g as TestProjectInlineConfiguration, f as TestUserConfig, W as WatcherTriggerPattern } from './chunks/reporters.d.BC86JJdB.js';
5
- import { V as VitestPluginContext } from './chunks/plugin.d.vcD4xbMS.js';
6
- import { F as FakeTimerInstallOpts } from './chunks/config.d._GBBbReY.js';
3
+ import { I as InlineConfig, c as CoverageV8Options, R as ResolvedCoverageOptions, U as UserWorkspaceConfig, d as UserProjectConfigFn, e as UserProjectConfigExport } from './chunks/reporters.d.DmP-iHLr.js';
4
+ export { a as TestProjectConfiguration, g as TestProjectInlineConfiguration, f as TestUserConfig, W as WatcherTriggerPattern } from './chunks/reporters.d.DmP-iHLr.js';
5
+ import { V as VitestPluginContext } from './chunks/plugin.d.CIk0YiKb.js';
6
+ import { F as FakeTimerInstallOpts } from './chunks/config.d.DacWrqWe.js';
7
7
  import '@vitest/runner';
8
8
  import '@vitest/utils';
9
9
  import './chunks/environment.d.2fYMoz3o.js';
10
10
  import 'node:stream';
11
- import 'node:console';
12
- import './chunks/browser.d.DOMmqJQx.js';
13
- import './chunks/worker.d.DYlqbejz.js';
14
- import 'vite/module-runner';
15
- import '@vitest/snapshot';
16
11
  import '@vitest/mocker';
17
12
  import '@vitest/utils/source-map';
13
+ import './chunks/browser.d.DtfyY9yS.js';
14
+ import './chunks/worker.d.B2r4Ln6p.js';
15
+ import 'vite/module-runner';
16
+ import '@vitest/snapshot';
18
17
  import '@vitest/pretty-format';
19
18
  import '@vitest/utils/diff';
20
- import 'chai';
19
+ import '@vitest/expect';
21
20
  import 'vitest/optional-types.js';
22
21
  import './chunks/benchmark.d.DAaHLpsq.js';
23
22
  import '@vitest/runner/utils';
@@ -25,6 +24,7 @@ import 'tinybench';
25
24
  import './chunks/coverage.d.BZtK59WP.js';
26
25
  import '@vitest/snapshot/manager';
27
26
  import 'node:fs';
27
+ import 'node:console';
28
28
 
29
29
  /* eslint-disable unused-imports/no-unused-vars */
30
30