vitest 3.1.0-beta.1 → 3.1.0-beta.2

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/dist/browser.js +4 -4
  2. package/dist/chunks/base.CylSMlTD.js +41 -0
  3. package/dist/chunks/benchmark.BKUatJGy.js +39 -0
  4. package/dist/chunks/cac.JtTXbKz0.js +1525 -0
  5. package/dist/chunks/{cli-api.BwkkJsRe.js → cli-api.BTtPTYMs.js} +4638 -5072
  6. package/dist/chunks/console.D6t261w0.js +173 -0
  7. package/dist/chunks/constants.BZZyIeIE.js +43 -0
  8. package/dist/chunks/coverage.0iPg4Wrz.js +33 -0
  9. package/dist/chunks/{coverage.gV8doR2Y.js → coverage.C2ohxaN0.js} +2216 -2479
  10. package/dist/chunks/creator.BEXek7yQ.js +640 -0
  11. package/dist/chunks/date.CDOsz-HY.js +53 -0
  12. package/dist/chunks/defaults.DmfNPoe5.js +114 -0
  13. package/dist/chunks/{env.D4Lgay0q.js → env.Dq0hM4Xv.js} +1 -1
  14. package/dist/chunks/execute.DZKwfrTs.js +791 -0
  15. package/dist/chunks/git.DXfdBEfR.js +74 -0
  16. package/dist/chunks/{globals.BEpDe-k3.js → globals.DCbUWjip.js} +10 -10
  17. package/dist/chunks/{index.D7Ny8f_s.js → index.BDobFbcz.js} +6 -7
  18. package/dist/chunks/index.DFXFpH3w.js +607 -0
  19. package/dist/chunks/index.VfYQ6MXY.js +104 -0
  20. package/dist/chunks/index.ZIOEXBQB.js +2382 -0
  21. package/dist/chunks/inspector.DbDkSkFn.js +54 -0
  22. package/dist/chunks/node.IqGoMrm4.js +15 -0
  23. package/dist/chunks/{reporters.d.r7poTZjA.d.ts → reporters.d.5g6jXhoW.d.ts} +14 -3
  24. package/dist/chunks/rpc.DGgL5dw7.js +92 -0
  25. package/dist/chunks/run-once.I7PpBOk1.js +47 -0
  26. package/dist/chunks/runBaseTests.CqmKSG99.js +134 -0
  27. package/dist/chunks/setup-common.DEGDGBiA.js +88 -0
  28. package/dist/chunks/{typechecker.BlF3eHsb.js → typechecker.C2IpOhid.js} +620 -622
  29. package/dist/chunks/utils.BfxieIyZ.js +66 -0
  30. package/dist/chunks/utils.CtocqOoE.js +72 -0
  31. package/dist/chunks/utils.OLmtDstN.js +194 -0
  32. package/dist/chunks/{vi.nSCvwQ7l.js → vi.B-PuvDzu.js} +878 -1019
  33. package/dist/chunks/vite.d.Dh1jE-_V.d.ts +23 -0
  34. package/dist/chunks/vm.BW5voG-u.js +789 -0
  35. package/dist/cli.js +2 -2
  36. package/dist/config.cjs +97 -103
  37. package/dist/config.d.ts +3 -3
  38. package/dist/config.js +6 -6
  39. package/dist/coverage.d.ts +1 -1
  40. package/dist/coverage.js +6 -6
  41. package/dist/environments.js +1 -1
  42. package/dist/execute.js +1 -1
  43. package/dist/index.d.ts +2 -2
  44. package/dist/index.js +6 -6
  45. package/dist/node.d.ts +3 -3
  46. package/dist/node.js +36 -45
  47. package/dist/path.js +1 -4
  48. package/dist/reporters.d.ts +1 -1
  49. package/dist/reporters.js +4 -4
  50. package/dist/runners.js +231 -267
  51. package/dist/snapshot.js +2 -2
  52. package/dist/suite.js +2 -2
  53. package/dist/worker.js +98 -114
  54. package/dist/workers/forks.js +22 -22
  55. package/dist/workers/runVmTests.js +61 -66
  56. package/dist/workers/threads.js +13 -13
  57. package/dist/workers/vmForks.js +24 -24
  58. package/dist/workers/vmThreads.js +15 -15
  59. package/dist/workers.js +10 -10
  60. package/package.json +11 -11
  61. package/dist/chunks/base.DV59CbtV.js +0 -45
  62. package/dist/chunks/benchmark.DL72EVN-.js +0 -40
  63. package/dist/chunks/cac.BjmXy7OV.js +0 -1664
  64. package/dist/chunks/console.CN7AiMGV.js +0 -179
  65. package/dist/chunks/constants.DTYd6dNH.js +0 -46
  66. package/dist/chunks/coverage.A3sS5-Wm.js +0 -40
  67. package/dist/chunks/creator.BsBnpTzI.js +0 -670
  68. package/dist/chunks/date.W2xKR2qe.js +0 -53
  69. package/dist/chunks/defaults.C2Ndd9wx.js +0 -119
  70. package/dist/chunks/execute.eDH0aFFd.js +0 -839
  71. package/dist/chunks/git.B5SDxu-n.js +0 -69
  72. package/dist/chunks/index.DOyx6FYJ.js +0 -2551
  73. package/dist/chunks/index.K90BXFOx.js +0 -658
  74. package/dist/chunks/index.uXkkC4xl.js +0 -111
  75. package/dist/chunks/inspector.DKLceBVD.js +0 -54
  76. package/dist/chunks/node.AKq966Jp.js +0 -15
  77. package/dist/chunks/rpc.TVf73xOu.js +0 -102
  78. package/dist/chunks/run-once.2ogXb3JV.js +0 -28
  79. package/dist/chunks/runBaseTests.BVrL_ow3.js +0 -142
  80. package/dist/chunks/setup-common.CPvtqi8q.js +0 -96
  81. package/dist/chunks/utils.C8RiOc4B.js +0 -77
  82. package/dist/chunks/utils.Cn0zI1t3.js +0 -68
  83. package/dist/chunks/utils.bLM2atbD.js +0 -198
  84. package/dist/chunks/vite.d.Fvq-NZoa.d.ts +0 -11
  85. package/dist/chunks/vm.jEFQDlX_.js +0 -852
@@ -2,146 +2,116 @@ import { equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, J
2
2
  import { getCurrentTest } from '@vitest/runner';
3
3
  import { getNames, getTestName } from '@vitest/runner/utils';
4
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.C8RiOc4B.js';
5
+ import { g as getWorkerState, a as getCurrentEnvironment, i as isChildProcess, w as waitForImportsToResolve, r as resetModules } from './utils.CtocqOoE.js';
6
6
  import { getSafeTimers, assertTypes, createSimpleStackTrace } from '@vitest/utils';
7
7
  import { g as getDefaultExportFromCjs, c as commonjsGlobal } from './_commonjsHelpers.BFTU3MAI.js';
8
8
  import { stripSnapshotIndentation, addSerializer, SnapshotClient } from '@vitest/snapshot';
9
9
  import '@vitest/utils/error';
10
10
  import { fn, spyOn, mocks, isMockFunction } from '@vitest/spy';
11
11
  import { parseSingleStack } from '@vitest/utils/source-map';
12
- import { R as RealDate, r as resetDate, m as mockDate } from './date.W2xKR2qe.js';
12
+ import { R as RealDate, r as resetDate, m as mockDate } from './date.CDOsz-HY.js';
13
13
 
14
14
  const unsupported = [
15
- // .poll is meant to retry matchers until they succeed, and
16
- // snapshots will always succeed as long as the poll method doesn't throw an error
17
- // in this case using the `vi.waitFor` method is more appropriate
18
- "matchSnapshot",
19
- "toMatchSnapshot",
20
- "toMatchInlineSnapshot",
21
- "toThrowErrorMatchingSnapshot",
22
- "toThrowErrorMatchingInlineSnapshot",
23
- // toThrow will never succeed because we call the poll callback until it doesn't throw
24
- "throws",
25
- "Throw",
26
- "throw",
27
- "toThrow",
28
- "toThrowError"
29
- // these are not supported because you can call them without `.poll`,
30
- // we throw an error inside the rejects/resolves methods to prevent this
31
- // rejects,
32
- // resolves
15
+ "matchSnapshot",
16
+ "toMatchSnapshot",
17
+ "toMatchInlineSnapshot",
18
+ "toThrowErrorMatchingSnapshot",
19
+ "toThrowErrorMatchingInlineSnapshot",
20
+ "throws",
21
+ "Throw",
22
+ "throw",
23
+ "toThrow",
24
+ "toThrowError"
33
25
  ];
34
26
  function createExpectPoll(expect) {
35
- return function poll(fn, options = {}) {
36
- const state = getWorkerState();
37
- const defaults = state.config.expect?.poll ?? {};
38
- const {
39
- interval = defaults.interval ?? 50,
40
- timeout = defaults.timeout ?? 1e3,
41
- message
42
- } = options;
43
- const assertion = expect(null, message).withContext({
44
- poll: true
45
- });
46
- fn = fn.bind(assertion);
47
- const test = chai$1.util.flag(assertion, "vitest-test");
48
- if (!test) {
49
- throw new Error("expect.poll() must be called inside a test");
50
- }
51
- const proxy = new Proxy(assertion, {
52
- get(target, key, receiver) {
53
- const assertionFunction = Reflect.get(target, key, receiver);
54
- if (typeof assertionFunction !== "function") {
55
- return assertionFunction instanceof chai$1.Assertion ? proxy : assertionFunction;
56
- }
57
- if (key === "assert") {
58
- return assertionFunction;
59
- }
60
- if (typeof key === "string" && unsupported.includes(key)) {
61
- throw new SyntaxError(
62
- `expect.poll() is not supported in combination with .${key}(). Use vi.waitFor() if your assertion condition is unstable.`
63
- );
64
- }
65
- return function(...args) {
66
- const STACK_TRACE_ERROR = new Error("STACK_TRACE_ERROR");
67
- const promise = () => new Promise((resolve, reject) => {
68
- let intervalId;
69
- let timeoutId;
70
- let lastError;
71
- const { setTimeout, clearTimeout } = getSafeTimers();
72
- const check = async () => {
73
- try {
74
- chai$1.util.flag(assertion, "_name", key);
75
- const obj = await fn();
76
- chai$1.util.flag(assertion, "object", obj);
77
- resolve(await assertionFunction.call(assertion, ...args));
78
- clearTimeout(intervalId);
79
- clearTimeout(timeoutId);
80
- } catch (err) {
81
- lastError = err;
82
- if (!chai$1.util.flag(assertion, "_isLastPollAttempt")) {
83
- intervalId = setTimeout(check, interval);
84
- }
85
- }
86
- };
87
- timeoutId = setTimeout(() => {
88
- clearTimeout(intervalId);
89
- chai$1.util.flag(assertion, "_isLastPollAttempt", true);
90
- const rejectWithCause = (cause) => {
91
- reject(
92
- copyStackTrace$1(
93
- new Error("Matcher did not succeed in time.", {
94
- cause
95
- }),
96
- STACK_TRACE_ERROR
97
- )
98
- );
99
- };
100
- check().then(() => rejectWithCause(lastError)).catch((e) => rejectWithCause(e));
101
- }, timeout);
102
- check();
103
- });
104
- let awaited = false;
105
- test.onFinished ??= [];
106
- test.onFinished.push(() => {
107
- if (!awaited) {
108
- const negated = chai$1.util.flag(assertion, "negate") ? "not." : "";
109
- const name = chai$1.util.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)";
110
- const assertionString = `expect.${name}.${negated}${String(key)}()`;
111
- const error = new Error(
112
- `${assertionString} was not awaited. This assertion is asynchronous and must be awaited; otherwise, it is not executed to avoid unhandled rejections:
113
-
114
- await ${assertionString}
115
- `
116
- );
117
- throw copyStackTrace$1(error, STACK_TRACE_ERROR);
118
- }
119
- });
120
- let resultPromise;
121
- return {
122
- then(onFulfilled, onRejected) {
123
- awaited = true;
124
- return (resultPromise ||= promise()).then(onFulfilled, onRejected);
125
- },
126
- catch(onRejected) {
127
- return (resultPromise ||= promise()).catch(onRejected);
128
- },
129
- finally(onFinally) {
130
- return (resultPromise ||= promise()).finally(onFinally);
131
- },
132
- [Symbol.toStringTag]: "Promise"
133
- };
134
- };
135
- }
136
- });
137
- return proxy;
138
- };
27
+ return function poll(fn, options = {}) {
28
+ const state = getWorkerState();
29
+ const defaults = state.config.expect?.poll ?? {};
30
+ const { interval = defaults.interval ?? 50, timeout = defaults.timeout ?? 1e3, message } = options;
31
+ const assertion = expect(null, message).withContext({ poll: true });
32
+ fn = fn.bind(assertion);
33
+ const test = chai$1.util.flag(assertion, "vitest-test");
34
+ if (!test) {
35
+ throw new Error("expect.poll() must be called inside a test");
36
+ }
37
+ const proxy = new Proxy(assertion, { get(target, key, receiver) {
38
+ const assertionFunction = Reflect.get(target, key, receiver);
39
+ if (typeof assertionFunction !== "function") {
40
+ return assertionFunction instanceof chai$1.Assertion ? proxy : assertionFunction;
41
+ }
42
+ if (key === "assert") {
43
+ return assertionFunction;
44
+ }
45
+ if (typeof key === "string" && unsupported.includes(key)) {
46
+ throw new SyntaxError(`expect.poll() is not supported in combination with .${key}(). Use vi.waitFor() if your assertion condition is unstable.`);
47
+ }
48
+ return function(...args) {
49
+ const STACK_TRACE_ERROR = new Error("STACK_TRACE_ERROR");
50
+ const promise = () => new Promise((resolve, reject) => {
51
+ let intervalId;
52
+ let timeoutId;
53
+ let lastError;
54
+ const { setTimeout, clearTimeout } = getSafeTimers();
55
+ const check = async () => {
56
+ try {
57
+ chai$1.util.flag(assertion, "_name", key);
58
+ const obj = await fn();
59
+ chai$1.util.flag(assertion, "object", obj);
60
+ resolve(await assertionFunction.call(assertion, ...args));
61
+ clearTimeout(intervalId);
62
+ clearTimeout(timeoutId);
63
+ } catch (err) {
64
+ lastError = err;
65
+ if (!chai$1.util.flag(assertion, "_isLastPollAttempt")) {
66
+ intervalId = setTimeout(check, interval);
67
+ }
68
+ }
69
+ };
70
+ timeoutId = setTimeout(() => {
71
+ clearTimeout(intervalId);
72
+ chai$1.util.flag(assertion, "_isLastPollAttempt", true);
73
+ const rejectWithCause = (cause) => {
74
+ reject(copyStackTrace$1(new Error("Matcher did not succeed in time.", { cause }), STACK_TRACE_ERROR));
75
+ };
76
+ check().then(() => rejectWithCause(lastError)).catch((e) => rejectWithCause(e));
77
+ }, timeout);
78
+ check();
79
+ });
80
+ let awaited = false;
81
+ test.onFinished ??= [];
82
+ test.onFinished.push(() => {
83
+ if (!awaited) {
84
+ const negated = chai$1.util.flag(assertion, "negate") ? "not." : "";
85
+ const name = chai$1.util.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)";
86
+ const assertionString = `expect.${name}.${negated}${String(key)}()`;
87
+ const error = new Error(`${assertionString} was not awaited. This assertion is asynchronous and must be awaited; otherwise, it is not executed to avoid unhandled rejections:\n\nawait ${assertionString}\n`);
88
+ throw copyStackTrace$1(error, STACK_TRACE_ERROR);
89
+ }
90
+ });
91
+ let resultPromise;
92
+ return {
93
+ then(onFulfilled, onRejected) {
94
+ awaited = true;
95
+ return (resultPromise ||= promise()).then(onFulfilled, onRejected);
96
+ },
97
+ catch(onRejected) {
98
+ return (resultPromise ||= promise()).catch(onRejected);
99
+ },
100
+ finally(onFinally) {
101
+ return (resultPromise ||= promise()).finally(onFinally);
102
+ },
103
+ [Symbol.toStringTag]: "Promise"
104
+ };
105
+ };
106
+ } });
107
+ return proxy;
108
+ };
139
109
  }
140
110
  function copyStackTrace$1(target, source) {
141
- if (source.stack !== void 0) {
142
- target.stack = source.stack.replace(source.message, target.message);
143
- }
144
- return target;
111
+ if (source.stack !== undefined) {
112
+ target.stack = source.stack.replace(source.message, target.message);
113
+ }
114
+ return target;
145
115
  }
146
116
 
147
117
  function commonjsRequire(path) {
@@ -244,258 +214,219 @@ var chaiSubsetExports = requireChaiSubset();
244
214
  var Subset = /*@__PURE__*/getDefaultExportFromCjs(chaiSubsetExports);
245
215
 
246
216
  function createAssertionMessage(util, assertion, hasArgs) {
247
- const not = util.flag(assertion, "negate") ? "not." : "";
248
- const name = `${util.flag(assertion, "_name")}(${"expected" })`;
249
- const promiseName = util.flag(assertion, "promise");
250
- const promise = promiseName ? `.${promiseName}` : "";
251
- return `expect(actual)${promise}.${not}${name}`;
217
+ const not = util.flag(assertion, "negate") ? "not." : "";
218
+ const name = `${util.flag(assertion, "_name")}(${"expected" })`;
219
+ const promiseName = util.flag(assertion, "promise");
220
+ const promise = promiseName ? `.${promiseName}` : "";
221
+ return `expect(actual)${promise}.${not}${name}`;
252
222
  }
253
223
  function recordAsyncExpect(_test, promise, assertion, error) {
254
- const test = _test;
255
- if (test && promise instanceof Promise) {
256
- promise = promise.finally(() => {
257
- if (!test.promises) {
258
- return;
259
- }
260
- const index = test.promises.indexOf(promise);
261
- if (index !== -1) {
262
- test.promises.splice(index, 1);
263
- }
264
- });
265
- if (!test.promises) {
266
- test.promises = [];
267
- }
268
- test.promises.push(promise);
269
- let resolved = false;
270
- test.onFinished ??= [];
271
- test.onFinished.push(() => {
272
- if (!resolved) {
273
- const processor = globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || "");
274
- const stack = processor(error.stack);
275
- console.warn([
276
- `Promise returned by \`${assertion}\` was not awaited. `,
277
- "Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ",
278
- "Please remember to await the assertion.\n",
279
- stack
280
- ].join(""));
281
- }
282
- });
283
- return {
284
- then(onFulfilled, onRejected) {
285
- resolved = true;
286
- return promise.then(onFulfilled, onRejected);
287
- },
288
- catch(onRejected) {
289
- return promise.catch(onRejected);
290
- },
291
- finally(onFinally) {
292
- return promise.finally(onFinally);
293
- },
294
- [Symbol.toStringTag]: "Promise"
295
- };
296
- }
297
- return promise;
224
+ const test = _test;
225
+ if (test && promise instanceof Promise) {
226
+ promise = promise.finally(() => {
227
+ if (!test.promises) {
228
+ return;
229
+ }
230
+ const index = test.promises.indexOf(promise);
231
+ if (index !== -1) {
232
+ test.promises.splice(index, 1);
233
+ }
234
+ });
235
+ if (!test.promises) {
236
+ test.promises = [];
237
+ }
238
+ test.promises.push(promise);
239
+ let resolved = false;
240
+ test.onFinished ??= [];
241
+ test.onFinished.push(() => {
242
+ if (!resolved) {
243
+ const processor = globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || "");
244
+ const stack = processor(error.stack);
245
+ console.warn([
246
+ `Promise returned by \`${assertion}\` was not awaited. `,
247
+ "Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ",
248
+ "Please remember to await the assertion.\n",
249
+ stack
250
+ ].join(""));
251
+ }
252
+ });
253
+ return {
254
+ then(onFulfilled, onRejected) {
255
+ resolved = true;
256
+ return promise.then(onFulfilled, onRejected);
257
+ },
258
+ catch(onRejected) {
259
+ return promise.catch(onRejected);
260
+ },
261
+ finally(onFinally) {
262
+ return promise.finally(onFinally);
263
+ },
264
+ [Symbol.toStringTag]: "Promise"
265
+ };
266
+ }
267
+ return promise;
298
268
  }
299
269
 
300
270
  let _client;
301
271
  function getSnapshotClient() {
302
- if (!_client) {
303
- _client = new SnapshotClient({
304
- isEqual: (received, expected) => {
305
- return equals(received, expected, [iterableEquality, subsetEquality]);
306
- }
307
- });
308
- }
309
- return _client;
272
+ if (!_client) {
273
+ _client = new SnapshotClient({ isEqual: (received, expected) => {
274
+ return equals(received, expected, [iterableEquality, subsetEquality]);
275
+ } });
276
+ }
277
+ return _client;
310
278
  }
311
279
  function getError(expected, promise) {
312
- if (typeof expected !== "function") {
313
- if (!promise) {
314
- throw new Error(
315
- `expected must be a function, received ${typeof expected}`
316
- );
317
- }
318
- return expected;
319
- }
320
- try {
321
- expected();
322
- } catch (e) {
323
- return e;
324
- }
325
- throw new Error("snapshot function didn't throw");
280
+ if (typeof expected !== "function") {
281
+ if (!promise) {
282
+ throw new Error(`expected must be a function, received ${typeof expected}`);
283
+ }
284
+ return expected;
285
+ }
286
+ try {
287
+ expected();
288
+ } catch (e) {
289
+ return e;
290
+ }
291
+ throw new Error("snapshot function didn't throw");
326
292
  }
327
293
  function getTestNames(test) {
328
- return {
329
- filepath: test.file.filepath,
330
- name: getNames(test).slice(1).join(" > "),
331
- testId: test.id
332
- };
294
+ return {
295
+ filepath: test.file.filepath,
296
+ name: getNames(test).slice(1).join(" > "),
297
+ testId: test.id
298
+ };
333
299
  }
334
300
  const SnapshotPlugin = (chai, utils) => {
335
- function getTest(assertionName, obj) {
336
- const test = utils.flag(obj, "vitest-test");
337
- if (!test) {
338
- throw new Error(`'${assertionName}' cannot be used without test context`);
339
- }
340
- return test;
341
- }
342
- for (const key of ["matchSnapshot", "toMatchSnapshot"]) {
343
- utils.addMethod(
344
- chai.Assertion.prototype,
345
- key,
346
- function(properties, message) {
347
- utils.flag(this, "_name", key);
348
- const isNot = utils.flag(this, "negate");
349
- if (isNot) {
350
- throw new Error(`${key} cannot be used with "not"`);
351
- }
352
- const expected = utils.flag(this, "object");
353
- const test = getTest(key, this);
354
- if (typeof properties === "string" && typeof message === "undefined") {
355
- message = properties;
356
- properties = void 0;
357
- }
358
- const errorMessage = utils.flag(this, "message");
359
- getSnapshotClient().assert({
360
- received: expected,
361
- message,
362
- isInline: false,
363
- properties,
364
- errorMessage,
365
- ...getTestNames(test)
366
- });
367
- }
368
- );
369
- }
370
- utils.addMethod(
371
- chai.Assertion.prototype,
372
- "toMatchFileSnapshot",
373
- function(file, message) {
374
- utils.flag(this, "_name", "toMatchFileSnapshot");
375
- const isNot = utils.flag(this, "negate");
376
- if (isNot) {
377
- throw new Error('toMatchFileSnapshot cannot be used with "not"');
378
- }
379
- const error = new Error("resolves");
380
- const expected = utils.flag(this, "object");
381
- const test = getTest("toMatchFileSnapshot", this);
382
- const errorMessage = utils.flag(this, "message");
383
- const promise = getSnapshotClient().assertRaw({
384
- received: expected,
385
- message,
386
- isInline: false,
387
- rawSnapshot: {
388
- file
389
- },
390
- errorMessage,
391
- ...getTestNames(test)
392
- });
393
- return recordAsyncExpect(
394
- test,
395
- promise,
396
- createAssertionMessage(utils, this),
397
- error
398
- );
399
- }
400
- );
401
- utils.addMethod(
402
- chai.Assertion.prototype,
403
- "toMatchInlineSnapshot",
404
- function __INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
405
- utils.flag(this, "_name", "toMatchInlineSnapshot");
406
- const isNot = utils.flag(this, "negate");
407
- if (isNot) {
408
- throw new Error('toMatchInlineSnapshot cannot be used with "not"');
409
- }
410
- const test = getTest("toMatchInlineSnapshot", this);
411
- const isInsideEach = test.each || test.suite?.each;
412
- if (isInsideEach) {
413
- throw new Error(
414
- "InlineSnapshot cannot be used inside of test.each or describe.each"
415
- );
416
- }
417
- const expected = utils.flag(this, "object");
418
- const error = utils.flag(this, "error");
419
- if (typeof properties === "string") {
420
- message = inlineSnapshot;
421
- inlineSnapshot = properties;
422
- properties = void 0;
423
- }
424
- if (inlineSnapshot) {
425
- inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
426
- }
427
- const errorMessage = utils.flag(this, "message");
428
- getSnapshotClient().assert({
429
- received: expected,
430
- message,
431
- isInline: true,
432
- properties,
433
- inlineSnapshot,
434
- error,
435
- errorMessage,
436
- ...getTestNames(test)
437
- });
438
- }
439
- );
440
- utils.addMethod(
441
- chai.Assertion.prototype,
442
- "toThrowErrorMatchingSnapshot",
443
- function(message) {
444
- utils.flag(this, "_name", "toThrowErrorMatchingSnapshot");
445
- const isNot = utils.flag(this, "negate");
446
- if (isNot) {
447
- throw new Error(
448
- 'toThrowErrorMatchingSnapshot cannot be used with "not"'
449
- );
450
- }
451
- const expected = utils.flag(this, "object");
452
- const test = getTest("toThrowErrorMatchingSnapshot", this);
453
- const promise = utils.flag(this, "promise");
454
- const errorMessage = utils.flag(this, "message");
455
- getSnapshotClient().assert({
456
- received: getError(expected, promise),
457
- message,
458
- errorMessage,
459
- ...getTestNames(test)
460
- });
461
- }
462
- );
463
- utils.addMethod(
464
- chai.Assertion.prototype,
465
- "toThrowErrorMatchingInlineSnapshot",
466
- function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
467
- const isNot = utils.flag(this, "negate");
468
- if (isNot) {
469
- throw new Error(
470
- 'toThrowErrorMatchingInlineSnapshot cannot be used with "not"'
471
- );
472
- }
473
- const test = getTest("toThrowErrorMatchingInlineSnapshot", this);
474
- const isInsideEach = test.each || test.suite?.each;
475
- if (isInsideEach) {
476
- throw new Error(
477
- "InlineSnapshot cannot be used inside of test.each or describe.each"
478
- );
479
- }
480
- const expected = utils.flag(this, "object");
481
- const error = utils.flag(this, "error");
482
- const promise = utils.flag(this, "promise");
483
- const errorMessage = utils.flag(this, "message");
484
- if (inlineSnapshot) {
485
- inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
486
- }
487
- getSnapshotClient().assert({
488
- received: getError(expected, promise),
489
- message,
490
- inlineSnapshot,
491
- isInline: true,
492
- error,
493
- errorMessage,
494
- ...getTestNames(test)
495
- });
496
- }
497
- );
498
- utils.addMethod(chai.expect, "addSnapshotSerializer", addSerializer);
301
+ function getTest(assertionName, obj) {
302
+ const test = utils.flag(obj, "vitest-test");
303
+ if (!test) {
304
+ throw new Error(`'${assertionName}' cannot be used without test context`);
305
+ }
306
+ return test;
307
+ }
308
+ for (const key of ["matchSnapshot", "toMatchSnapshot"]) {
309
+ utils.addMethod(chai.Assertion.prototype, key, function(properties, message) {
310
+ utils.flag(this, "_name", key);
311
+ const isNot = utils.flag(this, "negate");
312
+ if (isNot) {
313
+ throw new Error(`${key} cannot be used with "not"`);
314
+ }
315
+ const expected = utils.flag(this, "object");
316
+ const test = getTest(key, this);
317
+ if (typeof properties === "string" && typeof message === "undefined") {
318
+ message = properties;
319
+ properties = undefined;
320
+ }
321
+ const errorMessage = utils.flag(this, "message");
322
+ getSnapshotClient().assert({
323
+ received: expected,
324
+ message,
325
+ isInline: false,
326
+ properties,
327
+ errorMessage,
328
+ ...getTestNames(test)
329
+ });
330
+ });
331
+ }
332
+ utils.addMethod(chai.Assertion.prototype, "toMatchFileSnapshot", function(file, message) {
333
+ utils.flag(this, "_name", "toMatchFileSnapshot");
334
+ const isNot = utils.flag(this, "negate");
335
+ if (isNot) {
336
+ throw new Error("toMatchFileSnapshot cannot be used with \"not\"");
337
+ }
338
+ const error = new Error("resolves");
339
+ const expected = utils.flag(this, "object");
340
+ const test = getTest("toMatchFileSnapshot", this);
341
+ const errorMessage = utils.flag(this, "message");
342
+ const promise = getSnapshotClient().assertRaw({
343
+ received: expected,
344
+ message,
345
+ isInline: false,
346
+ rawSnapshot: { file },
347
+ errorMessage,
348
+ ...getTestNames(test)
349
+ });
350
+ return recordAsyncExpect(test, promise, createAssertionMessage(utils, this), error);
351
+ });
352
+ utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", function __INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
353
+ utils.flag(this, "_name", "toMatchInlineSnapshot");
354
+ const isNot = utils.flag(this, "negate");
355
+ if (isNot) {
356
+ throw new Error("toMatchInlineSnapshot cannot be used with \"not\"");
357
+ }
358
+ const test = getTest("toMatchInlineSnapshot", this);
359
+ const isInsideEach = test.each || test.suite?.each;
360
+ if (isInsideEach) {
361
+ throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
362
+ }
363
+ const expected = utils.flag(this, "object");
364
+ const error = utils.flag(this, "error");
365
+ if (typeof properties === "string") {
366
+ message = inlineSnapshot;
367
+ inlineSnapshot = properties;
368
+ properties = undefined;
369
+ }
370
+ if (inlineSnapshot) {
371
+ inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
372
+ }
373
+ const errorMessage = utils.flag(this, "message");
374
+ getSnapshotClient().assert({
375
+ received: expected,
376
+ message,
377
+ isInline: true,
378
+ properties,
379
+ inlineSnapshot,
380
+ error,
381
+ errorMessage,
382
+ ...getTestNames(test)
383
+ });
384
+ });
385
+ utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingSnapshot", function(message) {
386
+ utils.flag(this, "_name", "toThrowErrorMatchingSnapshot");
387
+ const isNot = utils.flag(this, "negate");
388
+ if (isNot) {
389
+ throw new Error("toThrowErrorMatchingSnapshot cannot be used with \"not\"");
390
+ }
391
+ const expected = utils.flag(this, "object");
392
+ const test = getTest("toThrowErrorMatchingSnapshot", this);
393
+ const promise = utils.flag(this, "promise");
394
+ const errorMessage = utils.flag(this, "message");
395
+ getSnapshotClient().assert({
396
+ received: getError(expected, promise),
397
+ message,
398
+ errorMessage,
399
+ ...getTestNames(test)
400
+ });
401
+ });
402
+ utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingInlineSnapshot", function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
403
+ const isNot = utils.flag(this, "negate");
404
+ if (isNot) {
405
+ throw new Error("toThrowErrorMatchingInlineSnapshot cannot be used with \"not\"");
406
+ }
407
+ const test = getTest("toThrowErrorMatchingInlineSnapshot", this);
408
+ const isInsideEach = test.each || test.suite?.each;
409
+ if (isInsideEach) {
410
+ throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
411
+ }
412
+ const expected = utils.flag(this, "object");
413
+ const error = utils.flag(this, "error");
414
+ const promise = utils.flag(this, "promise");
415
+ const errorMessage = utils.flag(this, "message");
416
+ if (inlineSnapshot) {
417
+ inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
418
+ }
419
+ getSnapshotClient().assert({
420
+ received: getError(expected, promise),
421
+ message,
422
+ inlineSnapshot,
423
+ isInline: true,
424
+ error,
425
+ errorMessage,
426
+ ...getTestNames(test)
427
+ });
428
+ });
429
+ utils.addMethod(chai.expect, "addSnapshotSerializer", addSerializer);
499
430
  };
500
431
 
501
432
  chai$1.use(JestExtend);
@@ -505,87 +436,83 @@ chai$1.use(SnapshotPlugin);
505
436
  chai$1.use(JestAsymmetricMatchers);
506
437
 
507
438
  function createExpect(test) {
508
- const expect = (value, message) => {
509
- const { assertionCalls } = getState(expect);
510
- setState({ assertionCalls: assertionCalls + 1 }, expect);
511
- const assert2 = chai$1.expect(value, message);
512
- const _test = test || getCurrentTest();
513
- if (_test) {
514
- return assert2.withTest(_test);
515
- } else {
516
- return assert2;
517
- }
518
- };
519
- Object.assign(expect, chai$1.expect);
520
- Object.assign(expect, globalThis[ASYMMETRIC_MATCHERS_OBJECT]);
521
- expect.getState = () => getState(expect);
522
- expect.setState = (state) => setState(state, expect);
523
- const globalState = getState(globalThis[GLOBAL_EXPECT]) || {};
524
- setState(
525
- {
526
- // this should also add "snapshotState" that is added conditionally
527
- ...globalState,
528
- assertionCalls: 0,
529
- isExpectingAssertions: false,
530
- isExpectingAssertionsError: null,
531
- expectedAssertionsNumber: null,
532
- expectedAssertionsNumberErrorGen: null,
533
- environment: getCurrentEnvironment(),
534
- get testPath() {
535
- return getWorkerState().filepath;
536
- },
537
- currentTestName: test ? getTestName(test) : globalState.currentTestName
538
- },
539
- expect
540
- );
541
- expect.extend = (matchers) => chai$1.expect.extend(expect, matchers);
542
- expect.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters);
543
- expect.soft = (...args) => {
544
- return expect(...args).withContext({ soft: true });
545
- };
546
- expect.poll = createExpectPoll(expect);
547
- expect.unreachable = (message) => {
548
- chai$1.assert.fail(
549
- `expected${message ? ` "${message}" ` : " "}not to be reached`
550
- );
551
- };
552
- function assertions(expected) {
553
- const errorGen = () => new Error(
554
- `expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`
555
- );
556
- if (Error.captureStackTrace) {
557
- Error.captureStackTrace(errorGen(), assertions);
558
- }
559
- expect.setState({
560
- expectedAssertionsNumber: expected,
561
- expectedAssertionsNumberErrorGen: errorGen
562
- });
563
- }
564
- function hasAssertions() {
565
- const error = new Error("expected any number of assertion, but got none");
566
- if (Error.captureStackTrace) {
567
- Error.captureStackTrace(error, hasAssertions);
568
- }
569
- expect.setState({
570
- isExpectingAssertions: true,
571
- isExpectingAssertionsError: error
572
- });
573
- }
574
- chai$1.util.addMethod(expect, "assertions", assertions);
575
- chai$1.util.addMethod(expect, "hasAssertions", hasAssertions);
576
- expect.extend(customMatchers);
577
- return expect;
439
+ const expect = (value, message) => {
440
+ const { assertionCalls } = getState(expect);
441
+ setState({ assertionCalls: assertionCalls + 1 }, expect);
442
+ const assert = chai$1.expect(value, message);
443
+ const _test = test || getCurrentTest();
444
+ if (_test) {
445
+ return assert.withTest(_test);
446
+ } else {
447
+ return assert;
448
+ }
449
+ };
450
+ Object.assign(expect, chai$1.expect);
451
+ Object.assign(expect, globalThis[ASYMMETRIC_MATCHERS_OBJECT]);
452
+ expect.getState = () => getState(expect);
453
+ expect.setState = (state) => setState(state, expect);
454
+ const globalState = getState(globalThis[GLOBAL_EXPECT]) || {};
455
+ setState({
456
+ ...globalState,
457
+ assertionCalls: 0,
458
+ isExpectingAssertions: false,
459
+ isExpectingAssertionsError: null,
460
+ expectedAssertionsNumber: null,
461
+ expectedAssertionsNumberErrorGen: null,
462
+ environment: getCurrentEnvironment(),
463
+ get testPath() {
464
+ return getWorkerState().filepath;
465
+ },
466
+ currentTestName: test ? getTestName(test) : globalState.currentTestName
467
+ }, expect);
468
+ expect.extend = (matchers) => chai$1.expect.extend(expect, matchers);
469
+ expect.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters);
470
+ expect.soft = (...args) => {
471
+ return expect(...args).withContext({ soft: true });
472
+ };
473
+ expect.poll = createExpectPoll(expect);
474
+ expect.unreachable = (message) => {
475
+ chai$1.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
476
+ };
477
+ function assertions(expected) {
478
+ const errorGen = () => new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
479
+ if (Error.captureStackTrace) {
480
+ Error.captureStackTrace(errorGen(), assertions);
481
+ }
482
+ expect.setState({
483
+ expectedAssertionsNumber: expected,
484
+ expectedAssertionsNumberErrorGen: errorGen
485
+ });
486
+ }
487
+ function hasAssertions() {
488
+ const error = new Error("expected any number of assertion, but got none");
489
+ if (Error.captureStackTrace) {
490
+ Error.captureStackTrace(error, hasAssertions);
491
+ }
492
+ expect.setState({
493
+ isExpectingAssertions: true,
494
+ isExpectingAssertionsError: error
495
+ });
496
+ }
497
+ chai$1.util.addMethod(expect, "assertions", assertions);
498
+ chai$1.util.addMethod(expect, "hasAssertions", hasAssertions);
499
+ expect.extend(customMatchers);
500
+ return expect;
578
501
  }
579
502
  const globalExpect = createExpect();
580
503
  Object.defineProperty(globalThis, GLOBAL_EXPECT, {
581
- value: globalExpect,
582
- writable: true,
583
- configurable: true
504
+ value: globalExpect,
505
+ writable: true,
506
+ configurable: true
584
507
  });
585
508
 
509
+ /**
510
+ * Gives access to injected context provided from the main thread.
511
+ * This usually returns a value provided by `globalSetup` or an external library.
512
+ */
586
513
  function inject(key) {
587
- const workerState = getWorkerState();
588
- return workerState.providedContext[key];
514
+ const workerState = getWorkerState();
515
+ return workerState.providedContext[key];
589
516
  }
590
517
 
591
518
  var fakeTimersSrc = {};
@@ -3682,598 +3609,530 @@ function requireFakeTimersSrc () {
3682
3609
  var fakeTimersSrcExports = requireFakeTimersSrc();
3683
3610
 
3684
3611
  class FakeTimers {
3685
- _global;
3686
- _clock;
3687
- // | _fakingTime | _fakingDate |
3688
- // +-------------+-------------+
3689
- // | false | falsy | initial
3690
- // | false | truthy | vi.setSystemTime called first (for mocking only Date without fake timers)
3691
- // | true | falsy | vi.useFakeTimers called first
3692
- // | true | truthy | unreachable
3693
- _fakingTime;
3694
- _fakingDate;
3695
- _fakeTimers;
3696
- _userConfig;
3697
- _now = RealDate.now;
3698
- constructor({
3699
- global,
3700
- config
3701
- }) {
3702
- this._userConfig = config;
3703
- this._fakingDate = null;
3704
- this._fakingTime = false;
3705
- this._fakeTimers = fakeTimersSrcExports.withGlobal(global);
3706
- this._global = global;
3707
- }
3708
- clearAllTimers() {
3709
- if (this._fakingTime) {
3710
- this._clock.reset();
3711
- }
3712
- }
3713
- dispose() {
3714
- this.useRealTimers();
3715
- }
3716
- runAllTimers() {
3717
- if (this._checkFakeTimers()) {
3718
- this._clock.runAll();
3719
- }
3720
- }
3721
- async runAllTimersAsync() {
3722
- if (this._checkFakeTimers()) {
3723
- await this._clock.runAllAsync();
3724
- }
3725
- }
3726
- runOnlyPendingTimers() {
3727
- if (this._checkFakeTimers()) {
3728
- this._clock.runToLast();
3729
- }
3730
- }
3731
- async runOnlyPendingTimersAsync() {
3732
- if (this._checkFakeTimers()) {
3733
- await this._clock.runToLastAsync();
3734
- }
3735
- }
3736
- advanceTimersToNextTimer(steps = 1) {
3737
- if (this._checkFakeTimers()) {
3738
- for (let i = steps; i > 0; i--) {
3739
- this._clock.next();
3740
- this._clock.tick(0);
3741
- if (this._clock.countTimers() === 0) {
3742
- break;
3743
- }
3744
- }
3745
- }
3746
- }
3747
- async advanceTimersToNextTimerAsync(steps = 1) {
3748
- if (this._checkFakeTimers()) {
3749
- for (let i = steps; i > 0; i--) {
3750
- await this._clock.nextAsync();
3751
- this._clock.tick(0);
3752
- if (this._clock.countTimers() === 0) {
3753
- break;
3754
- }
3755
- }
3756
- }
3757
- }
3758
- advanceTimersByTime(msToRun) {
3759
- if (this._checkFakeTimers()) {
3760
- this._clock.tick(msToRun);
3761
- }
3762
- }
3763
- async advanceTimersByTimeAsync(msToRun) {
3764
- if (this._checkFakeTimers()) {
3765
- await this._clock.tickAsync(msToRun);
3766
- }
3767
- }
3768
- advanceTimersToNextFrame() {
3769
- if (this._checkFakeTimers()) {
3770
- this._clock.runToFrame();
3771
- }
3772
- }
3773
- runAllTicks() {
3774
- if (this._checkFakeTimers()) {
3775
- this._clock.runMicrotasks();
3776
- }
3777
- }
3778
- useRealTimers() {
3779
- if (this._fakingDate) {
3780
- resetDate();
3781
- this._fakingDate = null;
3782
- }
3783
- if (this._fakingTime) {
3784
- this._clock.uninstall();
3785
- this._fakingTime = false;
3786
- }
3787
- }
3788
- useFakeTimers() {
3789
- if (this._fakingDate) {
3790
- throw new Error(
3791
- '"setSystemTime" was called already and date was mocked. Reset timers using `vi.useRealTimers()` if you want to use fake timers again.'
3792
- );
3793
- }
3794
- if (!this._fakingTime) {
3795
- const toFake = Object.keys(this._fakeTimers.timers).filter(
3796
- (timer) => timer !== "nextTick" && timer !== "queueMicrotask"
3797
- );
3798
- if (this._userConfig?.toFake?.includes("nextTick") && isChildProcess()) {
3799
- throw new Error(
3800
- "process.nextTick cannot be mocked inside child_process"
3801
- );
3802
- }
3803
- this._clock = this._fakeTimers.install({
3804
- now: Date.now(),
3805
- ...this._userConfig,
3806
- toFake: this._userConfig?.toFake || toFake,
3807
- ignoreMissingTimers: true
3808
- });
3809
- this._fakingTime = true;
3810
- }
3811
- }
3812
- reset() {
3813
- if (this._checkFakeTimers()) {
3814
- const { now } = this._clock;
3815
- this._clock.reset();
3816
- this._clock.setSystemTime(now);
3817
- }
3818
- }
3819
- setSystemTime(now) {
3820
- const date = typeof now === "undefined" || now instanceof Date ? now : new Date(now);
3821
- if (this._fakingTime) {
3822
- this._clock.setSystemTime(date);
3823
- } else {
3824
- this._fakingDate = date ?? new Date(this.getRealSystemTime());
3825
- mockDate(this._fakingDate);
3826
- }
3827
- }
3828
- getMockedSystemTime() {
3829
- return this._fakingTime ? new Date(this._clock.now) : this._fakingDate;
3830
- }
3831
- getRealSystemTime() {
3832
- return this._now();
3833
- }
3834
- getTimerCount() {
3835
- if (this._checkFakeTimers()) {
3836
- return this._clock.countTimers();
3837
- }
3838
- return 0;
3839
- }
3840
- configure(config) {
3841
- this._userConfig = config;
3842
- }
3843
- isFakeTimers() {
3844
- return this._fakingTime;
3845
- }
3846
- _checkFakeTimers() {
3847
- if (!this._fakingTime) {
3848
- throw new Error(
3849
- 'Timers are not mocked. Try calling "vi.useFakeTimers()" first.'
3850
- );
3851
- }
3852
- return this._fakingTime;
3853
- }
3612
+ _global;
3613
+ _clock;
3614
+ _fakingTime;
3615
+ _fakingDate;
3616
+ _fakeTimers;
3617
+ _userConfig;
3618
+ _now = RealDate.now;
3619
+ constructor({ global, config }) {
3620
+ this._userConfig = config;
3621
+ this._fakingDate = null;
3622
+ this._fakingTime = false;
3623
+ this._fakeTimers = fakeTimersSrcExports.withGlobal(global);
3624
+ this._global = global;
3625
+ }
3626
+ clearAllTimers() {
3627
+ if (this._fakingTime) {
3628
+ this._clock.reset();
3629
+ }
3630
+ }
3631
+ dispose() {
3632
+ this.useRealTimers();
3633
+ }
3634
+ runAllTimers() {
3635
+ if (this._checkFakeTimers()) {
3636
+ this._clock.runAll();
3637
+ }
3638
+ }
3639
+ async runAllTimersAsync() {
3640
+ if (this._checkFakeTimers()) {
3641
+ await this._clock.runAllAsync();
3642
+ }
3643
+ }
3644
+ runOnlyPendingTimers() {
3645
+ if (this._checkFakeTimers()) {
3646
+ this._clock.runToLast();
3647
+ }
3648
+ }
3649
+ async runOnlyPendingTimersAsync() {
3650
+ if (this._checkFakeTimers()) {
3651
+ await this._clock.runToLastAsync();
3652
+ }
3653
+ }
3654
+ advanceTimersToNextTimer(steps = 1) {
3655
+ if (this._checkFakeTimers()) {
3656
+ for (let i = steps; i > 0; i--) {
3657
+ this._clock.next();
3658
+ this._clock.tick(0);
3659
+ if (this._clock.countTimers() === 0) {
3660
+ break;
3661
+ }
3662
+ }
3663
+ }
3664
+ }
3665
+ async advanceTimersToNextTimerAsync(steps = 1) {
3666
+ if (this._checkFakeTimers()) {
3667
+ for (let i = steps; i > 0; i--) {
3668
+ await this._clock.nextAsync();
3669
+ this._clock.tick(0);
3670
+ if (this._clock.countTimers() === 0) {
3671
+ break;
3672
+ }
3673
+ }
3674
+ }
3675
+ }
3676
+ advanceTimersByTime(msToRun) {
3677
+ if (this._checkFakeTimers()) {
3678
+ this._clock.tick(msToRun);
3679
+ }
3680
+ }
3681
+ async advanceTimersByTimeAsync(msToRun) {
3682
+ if (this._checkFakeTimers()) {
3683
+ await this._clock.tickAsync(msToRun);
3684
+ }
3685
+ }
3686
+ advanceTimersToNextFrame() {
3687
+ if (this._checkFakeTimers()) {
3688
+ this._clock.runToFrame();
3689
+ }
3690
+ }
3691
+ runAllTicks() {
3692
+ if (this._checkFakeTimers()) {
3693
+ this._clock.runMicrotasks();
3694
+ }
3695
+ }
3696
+ useRealTimers() {
3697
+ if (this._fakingDate) {
3698
+ resetDate();
3699
+ this._fakingDate = null;
3700
+ }
3701
+ if (this._fakingTime) {
3702
+ this._clock.uninstall();
3703
+ this._fakingTime = false;
3704
+ }
3705
+ }
3706
+ useFakeTimers() {
3707
+ if (this._fakingDate) {
3708
+ throw new Error("\"setSystemTime\" was called already and date was mocked. Reset timers using `vi.useRealTimers()` if you want to use fake timers again.");
3709
+ }
3710
+ if (!this._fakingTime) {
3711
+ const toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick" && timer !== "queueMicrotask");
3712
+ if (this._userConfig?.toFake?.includes("nextTick") && isChildProcess()) {
3713
+ throw new Error("process.nextTick cannot be mocked inside child_process");
3714
+ }
3715
+ this._clock = this._fakeTimers.install({
3716
+ now: Date.now(),
3717
+ ...this._userConfig,
3718
+ toFake: this._userConfig?.toFake || toFake,
3719
+ ignoreMissingTimers: true
3720
+ });
3721
+ this._fakingTime = true;
3722
+ }
3723
+ }
3724
+ reset() {
3725
+ if (this._checkFakeTimers()) {
3726
+ const { now } = this._clock;
3727
+ this._clock.reset();
3728
+ this._clock.setSystemTime(now);
3729
+ }
3730
+ }
3731
+ setSystemTime(now) {
3732
+ const date = typeof now === "undefined" || now instanceof Date ? now : new Date(now);
3733
+ if (this._fakingTime) {
3734
+ this._clock.setSystemTime(date);
3735
+ } else {
3736
+ this._fakingDate = date ?? new Date(this.getRealSystemTime());
3737
+ mockDate(this._fakingDate);
3738
+ }
3739
+ }
3740
+ getMockedSystemTime() {
3741
+ return this._fakingTime ? new Date(this._clock.now) : this._fakingDate;
3742
+ }
3743
+ getRealSystemTime() {
3744
+ return this._now();
3745
+ }
3746
+ getTimerCount() {
3747
+ if (this._checkFakeTimers()) {
3748
+ return this._clock.countTimers();
3749
+ }
3750
+ return 0;
3751
+ }
3752
+ configure(config) {
3753
+ this._userConfig = config;
3754
+ }
3755
+ isFakeTimers() {
3756
+ return this._fakingTime;
3757
+ }
3758
+ _checkFakeTimers() {
3759
+ if (!this._fakingTime) {
3760
+ throw new Error("Timers are not mocked. Try calling \"vi.useFakeTimers()\" first.");
3761
+ }
3762
+ return this._fakingTime;
3763
+ }
3854
3764
  }
3855
3765
 
3856
3766
  function copyStackTrace(target, source) {
3857
- if (source.stack !== void 0) {
3858
- target.stack = source.stack.replace(source.message, target.message);
3859
- }
3860
- return target;
3767
+ if (source.stack !== undefined) {
3768
+ target.stack = source.stack.replace(source.message, target.message);
3769
+ }
3770
+ return target;
3861
3771
  }
3862
3772
  function waitFor(callback, options = {}) {
3863
- const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
3864
- const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
3865
- const STACK_TRACE_ERROR = new Error("STACK_TRACE_ERROR");
3866
- return new Promise((resolve, reject) => {
3867
- let lastError;
3868
- let promiseStatus = "idle";
3869
- let timeoutId;
3870
- let intervalId;
3871
- const onResolve = (result) => {
3872
- if (timeoutId) {
3873
- clearTimeout(timeoutId);
3874
- }
3875
- if (intervalId) {
3876
- clearInterval(intervalId);
3877
- }
3878
- resolve(result);
3879
- };
3880
- const handleTimeout = () => {
3881
- if (intervalId) {
3882
- clearInterval(intervalId);
3883
- }
3884
- let error = lastError;
3885
- if (!error) {
3886
- error = copyStackTrace(
3887
- new Error("Timed out in waitFor!"),
3888
- STACK_TRACE_ERROR
3889
- );
3890
- }
3891
- reject(error);
3892
- };
3893
- const checkCallback = () => {
3894
- if (vi.isFakeTimers()) {
3895
- vi.advanceTimersByTime(interval);
3896
- }
3897
- if (promiseStatus === "pending") {
3898
- return;
3899
- }
3900
- try {
3901
- const result = callback();
3902
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
3903
- const thenable = result;
3904
- promiseStatus = "pending";
3905
- thenable.then(
3906
- (resolvedValue) => {
3907
- promiseStatus = "resolved";
3908
- onResolve(resolvedValue);
3909
- },
3910
- (rejectedValue) => {
3911
- promiseStatus = "rejected";
3912
- lastError = rejectedValue;
3913
- }
3914
- );
3915
- } else {
3916
- onResolve(result);
3917
- return true;
3918
- }
3919
- } catch (error) {
3920
- lastError = error;
3921
- }
3922
- };
3923
- if (checkCallback() === true) {
3924
- return;
3925
- }
3926
- timeoutId = setTimeout(handleTimeout, timeout);
3927
- intervalId = setInterval(checkCallback, interval);
3928
- });
3773
+ const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
3774
+ const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
3775
+ const STACK_TRACE_ERROR = new Error("STACK_TRACE_ERROR");
3776
+ return new Promise((resolve, reject) => {
3777
+ let lastError;
3778
+ let promiseStatus = "idle";
3779
+ let timeoutId;
3780
+ let intervalId;
3781
+ const onResolve = (result) => {
3782
+ if (timeoutId) {
3783
+ clearTimeout(timeoutId);
3784
+ }
3785
+ if (intervalId) {
3786
+ clearInterval(intervalId);
3787
+ }
3788
+ resolve(result);
3789
+ };
3790
+ const handleTimeout = () => {
3791
+ if (intervalId) {
3792
+ clearInterval(intervalId);
3793
+ }
3794
+ let error = lastError;
3795
+ if (!error) {
3796
+ error = copyStackTrace(new Error("Timed out in waitFor!"), STACK_TRACE_ERROR);
3797
+ }
3798
+ reject(error);
3799
+ };
3800
+ const checkCallback = () => {
3801
+ if (vi.isFakeTimers()) {
3802
+ vi.advanceTimersByTime(interval);
3803
+ }
3804
+ if (promiseStatus === "pending") {
3805
+ return;
3806
+ }
3807
+ try {
3808
+ const result = callback();
3809
+ if (result !== null && typeof result === "object" && typeof result.then === "function") {
3810
+ const thenable = result;
3811
+ promiseStatus = "pending";
3812
+ thenable.then((resolvedValue) => {
3813
+ promiseStatus = "resolved";
3814
+ onResolve(resolvedValue);
3815
+ }, (rejectedValue) => {
3816
+ promiseStatus = "rejected";
3817
+ lastError = rejectedValue;
3818
+ });
3819
+ } else {
3820
+ onResolve(result);
3821
+ return true;
3822
+ }
3823
+ } catch (error) {
3824
+ lastError = error;
3825
+ }
3826
+ };
3827
+ if (checkCallback() === true) {
3828
+ return;
3829
+ }
3830
+ timeoutId = setTimeout(handleTimeout, timeout);
3831
+ intervalId = setInterval(checkCallback, interval);
3832
+ });
3929
3833
  }
3930
3834
  function waitUntil(callback, options = {}) {
3931
- const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
3932
- const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
3933
- const STACK_TRACE_ERROR = new Error("STACK_TRACE_ERROR");
3934
- return new Promise((resolve, reject) => {
3935
- let promiseStatus = "idle";
3936
- let timeoutId;
3937
- let intervalId;
3938
- const onReject = (error) => {
3939
- if (intervalId) {
3940
- clearInterval(intervalId);
3941
- }
3942
- if (!error) {
3943
- error = copyStackTrace(
3944
- new Error("Timed out in waitUntil!"),
3945
- STACK_TRACE_ERROR
3946
- );
3947
- }
3948
- reject(error);
3949
- };
3950
- const onResolve = (result) => {
3951
- if (!result) {
3952
- return;
3953
- }
3954
- if (timeoutId) {
3955
- clearTimeout(timeoutId);
3956
- }
3957
- if (intervalId) {
3958
- clearInterval(intervalId);
3959
- }
3960
- resolve(result);
3961
- return true;
3962
- };
3963
- const checkCallback = () => {
3964
- if (vi.isFakeTimers()) {
3965
- vi.advanceTimersByTime(interval);
3966
- }
3967
- if (promiseStatus === "pending") {
3968
- return;
3969
- }
3970
- try {
3971
- const result = callback();
3972
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
3973
- const thenable = result;
3974
- promiseStatus = "pending";
3975
- thenable.then(
3976
- (resolvedValue) => {
3977
- promiseStatus = "resolved";
3978
- onResolve(resolvedValue);
3979
- },
3980
- (rejectedValue) => {
3981
- promiseStatus = "rejected";
3982
- onReject(rejectedValue);
3983
- }
3984
- );
3985
- } else {
3986
- return onResolve(result);
3987
- }
3988
- } catch (error) {
3989
- onReject(error);
3990
- }
3991
- };
3992
- if (checkCallback() === true) {
3993
- return;
3994
- }
3995
- timeoutId = setTimeout(onReject, timeout);
3996
- intervalId = setInterval(checkCallback, interval);
3997
- });
3835
+ const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
3836
+ const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
3837
+ const STACK_TRACE_ERROR = new Error("STACK_TRACE_ERROR");
3838
+ return new Promise((resolve, reject) => {
3839
+ let promiseStatus = "idle";
3840
+ let timeoutId;
3841
+ let intervalId;
3842
+ const onReject = (error) => {
3843
+ if (intervalId) {
3844
+ clearInterval(intervalId);
3845
+ }
3846
+ if (!error) {
3847
+ error = copyStackTrace(new Error("Timed out in waitUntil!"), STACK_TRACE_ERROR);
3848
+ }
3849
+ reject(error);
3850
+ };
3851
+ const onResolve = (result) => {
3852
+ if (!result) {
3853
+ return;
3854
+ }
3855
+ if (timeoutId) {
3856
+ clearTimeout(timeoutId);
3857
+ }
3858
+ if (intervalId) {
3859
+ clearInterval(intervalId);
3860
+ }
3861
+ resolve(result);
3862
+ return true;
3863
+ };
3864
+ const checkCallback = () => {
3865
+ if (vi.isFakeTimers()) {
3866
+ vi.advanceTimersByTime(interval);
3867
+ }
3868
+ if (promiseStatus === "pending") {
3869
+ return;
3870
+ }
3871
+ try {
3872
+ const result = callback();
3873
+ if (result !== null && typeof result === "object" && typeof result.then === "function") {
3874
+ const thenable = result;
3875
+ promiseStatus = "pending";
3876
+ thenable.then((resolvedValue) => {
3877
+ promiseStatus = "resolved";
3878
+ onResolve(resolvedValue);
3879
+ }, (rejectedValue) => {
3880
+ promiseStatus = "rejected";
3881
+ onReject(rejectedValue);
3882
+ });
3883
+ } else {
3884
+ return onResolve(result);
3885
+ }
3886
+ } catch (error) {
3887
+ onReject(error);
3888
+ }
3889
+ };
3890
+ if (checkCallback() === true) {
3891
+ return;
3892
+ }
3893
+ timeoutId = setTimeout(onReject, timeout);
3894
+ intervalId = setInterval(checkCallback, interval);
3895
+ });
3998
3896
  }
3999
3897
 
4000
3898
  function createVitest() {
4001
- let _config = null;
4002
- const workerState = getWorkerState();
4003
- let _timers;
4004
- const timers = () => _timers ||= new FakeTimers({
4005
- global: globalThis,
4006
- config: workerState.config.fakeTimers
4007
- });
4008
- const _stubsGlobal = /* @__PURE__ */ new Map();
4009
- const _stubsEnv = /* @__PURE__ */ new Map();
4010
- const _envBooleans = ["PROD", "DEV", "SSR"];
4011
- const utils = {
4012
- useFakeTimers(config) {
4013
- if (isChildProcess()) {
4014
- if (config?.toFake?.includes("nextTick") || workerState.config?.fakeTimers?.toFake?.includes("nextTick")) {
4015
- throw new Error(
4016
- 'vi.useFakeTimers({ toFake: ["nextTick"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.'
4017
- );
4018
- }
4019
- }
4020
- if (config) {
4021
- timers().configure({ ...workerState.config.fakeTimers, ...config });
4022
- } else {
4023
- timers().configure(workerState.config.fakeTimers);
4024
- }
4025
- timers().useFakeTimers();
4026
- return utils;
4027
- },
4028
- isFakeTimers() {
4029
- return timers().isFakeTimers();
4030
- },
4031
- useRealTimers() {
4032
- timers().useRealTimers();
4033
- return utils;
4034
- },
4035
- runOnlyPendingTimers() {
4036
- timers().runOnlyPendingTimers();
4037
- return utils;
4038
- },
4039
- async runOnlyPendingTimersAsync() {
4040
- await timers().runOnlyPendingTimersAsync();
4041
- return utils;
4042
- },
4043
- runAllTimers() {
4044
- timers().runAllTimers();
4045
- return utils;
4046
- },
4047
- async runAllTimersAsync() {
4048
- await timers().runAllTimersAsync();
4049
- return utils;
4050
- },
4051
- runAllTicks() {
4052
- timers().runAllTicks();
4053
- return utils;
4054
- },
4055
- advanceTimersByTime(ms) {
4056
- timers().advanceTimersByTime(ms);
4057
- return utils;
4058
- },
4059
- async advanceTimersByTimeAsync(ms) {
4060
- await timers().advanceTimersByTimeAsync(ms);
4061
- return utils;
4062
- },
4063
- advanceTimersToNextTimer() {
4064
- timers().advanceTimersToNextTimer();
4065
- return utils;
4066
- },
4067
- async advanceTimersToNextTimerAsync() {
4068
- await timers().advanceTimersToNextTimerAsync();
4069
- return utils;
4070
- },
4071
- advanceTimersToNextFrame() {
4072
- timers().advanceTimersToNextFrame();
4073
- return utils;
4074
- },
4075
- getTimerCount() {
4076
- return timers().getTimerCount();
4077
- },
4078
- setSystemTime(time) {
4079
- timers().setSystemTime(time);
4080
- return utils;
4081
- },
4082
- getMockedSystemTime() {
4083
- return timers().getMockedSystemTime();
4084
- },
4085
- getRealSystemTime() {
4086
- return timers().getRealSystemTime();
4087
- },
4088
- clearAllTimers() {
4089
- timers().clearAllTimers();
4090
- return utils;
4091
- },
4092
- // mocks
4093
- spyOn,
4094
- fn,
4095
- waitFor,
4096
- waitUntil,
4097
- hoisted(factory) {
4098
- assertTypes(factory, '"vi.hoisted" factory', ["function"]);
4099
- return factory();
4100
- },
4101
- mock(path, factory) {
4102
- if (typeof path !== "string") {
4103
- throw new TypeError(
4104
- `vi.mock() expects a string path, but received a ${typeof path}`
4105
- );
4106
- }
4107
- const importer = getImporter("mock");
4108
- _mocker().queueMock(
4109
- path,
4110
- importer,
4111
- typeof factory === "function" ? () => factory(
4112
- () => _mocker().importActual(
4113
- path,
4114
- importer,
4115
- _mocker().getMockContext().callstack
4116
- )
4117
- ) : factory
4118
- );
4119
- },
4120
- unmock(path) {
4121
- if (typeof path !== "string") {
4122
- throw new TypeError(
4123
- `vi.unmock() expects a string path, but received a ${typeof path}`
4124
- );
4125
- }
4126
- _mocker().queueUnmock(path, getImporter("unmock"));
4127
- },
4128
- doMock(path, factory) {
4129
- if (typeof path !== "string") {
4130
- throw new TypeError(
4131
- `vi.doMock() expects a string path, but received a ${typeof path}`
4132
- );
4133
- }
4134
- const importer = getImporter("doMock");
4135
- _mocker().queueMock(
4136
- path,
4137
- importer,
4138
- typeof factory === "function" ? () => factory(
4139
- () => _mocker().importActual(
4140
- path,
4141
- importer,
4142
- _mocker().getMockContext().callstack
4143
- )
4144
- ) : factory
4145
- );
4146
- },
4147
- doUnmock(path) {
4148
- if (typeof path !== "string") {
4149
- throw new TypeError(
4150
- `vi.doUnmock() expects a string path, but received a ${typeof path}`
4151
- );
4152
- }
4153
- _mocker().queueUnmock(path, getImporter("doUnmock"));
4154
- },
4155
- async importActual(path) {
4156
- return _mocker().importActual(
4157
- path,
4158
- getImporter("importActual"),
4159
- _mocker().getMockContext().callstack
4160
- );
4161
- },
4162
- async importMock(path) {
4163
- return _mocker().importMock(path, getImporter("importMock"));
4164
- },
4165
- // this is typed in the interface so it's not necessary to type it here
4166
- mocked(item, _options = {}) {
4167
- return item;
4168
- },
4169
- isMockFunction(fn2) {
4170
- return isMockFunction(fn2);
4171
- },
4172
- clearAllMocks() {
4173
- [...mocks].reverse().forEach((spy) => spy.mockClear());
4174
- return utils;
4175
- },
4176
- resetAllMocks() {
4177
- [...mocks].reverse().forEach((spy) => spy.mockReset());
4178
- return utils;
4179
- },
4180
- restoreAllMocks() {
4181
- [...mocks].reverse().forEach((spy) => spy.mockRestore());
4182
- return utils;
4183
- },
4184
- stubGlobal(name, value) {
4185
- if (!_stubsGlobal.has(name)) {
4186
- _stubsGlobal.set(
4187
- name,
4188
- Object.getOwnPropertyDescriptor(globalThis, name)
4189
- );
4190
- }
4191
- Object.defineProperty(globalThis, name, {
4192
- value,
4193
- writable: true,
4194
- configurable: true,
4195
- enumerable: true
4196
- });
4197
- return utils;
4198
- },
4199
- stubEnv(name, value) {
4200
- if (!_stubsEnv.has(name)) {
4201
- _stubsEnv.set(name, process.env[name]);
4202
- }
4203
- if (_envBooleans.includes(name)) {
4204
- process.env[name] = value ? "1" : "";
4205
- } else if (value === void 0) {
4206
- delete process.env[name];
4207
- } else {
4208
- process.env[name] = String(value);
4209
- }
4210
- return utils;
4211
- },
4212
- unstubAllGlobals() {
4213
- _stubsGlobal.forEach((original, name) => {
4214
- if (!original) {
4215
- Reflect.deleteProperty(globalThis, name);
4216
- } else {
4217
- Object.defineProperty(globalThis, name, original);
4218
- }
4219
- });
4220
- _stubsGlobal.clear();
4221
- return utils;
4222
- },
4223
- unstubAllEnvs() {
4224
- _stubsEnv.forEach((original, name) => {
4225
- if (original === void 0) {
4226
- delete process.env[name];
4227
- } else {
4228
- process.env[name] = original;
4229
- }
4230
- });
4231
- _stubsEnv.clear();
4232
- return utils;
4233
- },
4234
- resetModules() {
4235
- resetModules(workerState.moduleCache);
4236
- return utils;
4237
- },
4238
- async dynamicImportSettled() {
4239
- return waitForImportsToResolve();
4240
- },
4241
- setConfig(config) {
4242
- if (!_config) {
4243
- _config = { ...workerState.config };
4244
- }
4245
- Object.assign(workerState.config, config);
4246
- },
4247
- resetConfig() {
4248
- if (_config) {
4249
- Object.assign(workerState.config, _config);
4250
- }
4251
- }
4252
- };
4253
- return utils;
3899
+ let _config = null;
3900
+ const workerState = getWorkerState();
3901
+ let _timers;
3902
+ const timers = () => _timers ||= new FakeTimers({
3903
+ global: globalThis,
3904
+ config: workerState.config.fakeTimers
3905
+ });
3906
+ const _stubsGlobal = new Map();
3907
+ const _stubsEnv = new Map();
3908
+ const _envBooleans = [
3909
+ "PROD",
3910
+ "DEV",
3911
+ "SSR"
3912
+ ];
3913
+ const utils = {
3914
+ useFakeTimers(config) {
3915
+ if (isChildProcess()) {
3916
+ if (config?.toFake?.includes("nextTick") || workerState.config?.fakeTimers?.toFake?.includes("nextTick")) {
3917
+ throw new Error("vi.useFakeTimers({ toFake: [\"nextTick\"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.");
3918
+ }
3919
+ }
3920
+ if (config) {
3921
+ timers().configure({
3922
+ ...workerState.config.fakeTimers,
3923
+ ...config
3924
+ });
3925
+ } else {
3926
+ timers().configure(workerState.config.fakeTimers);
3927
+ }
3928
+ timers().useFakeTimers();
3929
+ return utils;
3930
+ },
3931
+ isFakeTimers() {
3932
+ return timers().isFakeTimers();
3933
+ },
3934
+ useRealTimers() {
3935
+ timers().useRealTimers();
3936
+ return utils;
3937
+ },
3938
+ runOnlyPendingTimers() {
3939
+ timers().runOnlyPendingTimers();
3940
+ return utils;
3941
+ },
3942
+ async runOnlyPendingTimersAsync() {
3943
+ await timers().runOnlyPendingTimersAsync();
3944
+ return utils;
3945
+ },
3946
+ runAllTimers() {
3947
+ timers().runAllTimers();
3948
+ return utils;
3949
+ },
3950
+ async runAllTimersAsync() {
3951
+ await timers().runAllTimersAsync();
3952
+ return utils;
3953
+ },
3954
+ runAllTicks() {
3955
+ timers().runAllTicks();
3956
+ return utils;
3957
+ },
3958
+ advanceTimersByTime(ms) {
3959
+ timers().advanceTimersByTime(ms);
3960
+ return utils;
3961
+ },
3962
+ async advanceTimersByTimeAsync(ms) {
3963
+ await timers().advanceTimersByTimeAsync(ms);
3964
+ return utils;
3965
+ },
3966
+ advanceTimersToNextTimer() {
3967
+ timers().advanceTimersToNextTimer();
3968
+ return utils;
3969
+ },
3970
+ async advanceTimersToNextTimerAsync() {
3971
+ await timers().advanceTimersToNextTimerAsync();
3972
+ return utils;
3973
+ },
3974
+ advanceTimersToNextFrame() {
3975
+ timers().advanceTimersToNextFrame();
3976
+ return utils;
3977
+ },
3978
+ getTimerCount() {
3979
+ return timers().getTimerCount();
3980
+ },
3981
+ setSystemTime(time) {
3982
+ timers().setSystemTime(time);
3983
+ return utils;
3984
+ },
3985
+ getMockedSystemTime() {
3986
+ return timers().getMockedSystemTime();
3987
+ },
3988
+ getRealSystemTime() {
3989
+ return timers().getRealSystemTime();
3990
+ },
3991
+ clearAllTimers() {
3992
+ timers().clearAllTimers();
3993
+ return utils;
3994
+ },
3995
+ spyOn,
3996
+ fn,
3997
+ waitFor,
3998
+ waitUntil,
3999
+ hoisted(factory) {
4000
+ assertTypes(factory, "\"vi.hoisted\" factory", ["function"]);
4001
+ return factory();
4002
+ },
4003
+ mock(path, factory) {
4004
+ if (typeof path !== "string") {
4005
+ throw new TypeError(`vi.mock() expects a string path, but received a ${typeof path}`);
4006
+ }
4007
+ const importer = getImporter("mock");
4008
+ _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer, _mocker().getMockContext().callstack)) : factory);
4009
+ },
4010
+ unmock(path) {
4011
+ if (typeof path !== "string") {
4012
+ throw new TypeError(`vi.unmock() expects a string path, but received a ${typeof path}`);
4013
+ }
4014
+ _mocker().queueUnmock(path, getImporter("unmock"));
4015
+ },
4016
+ doMock(path, factory) {
4017
+ if (typeof path !== "string") {
4018
+ throw new TypeError(`vi.doMock() expects a string path, but received a ${typeof path}`);
4019
+ }
4020
+ const importer = getImporter("doMock");
4021
+ _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer, _mocker().getMockContext().callstack)) : factory);
4022
+ },
4023
+ doUnmock(path) {
4024
+ if (typeof path !== "string") {
4025
+ throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`);
4026
+ }
4027
+ _mocker().queueUnmock(path, getImporter("doUnmock"));
4028
+ },
4029
+ async importActual(path) {
4030
+ return _mocker().importActual(path, getImporter("importActual"), _mocker().getMockContext().callstack);
4031
+ },
4032
+ async importMock(path) {
4033
+ return _mocker().importMock(path, getImporter("importMock"));
4034
+ },
4035
+ mocked(item, _options = {}) {
4036
+ return item;
4037
+ },
4038
+ isMockFunction(fn) {
4039
+ return isMockFunction(fn);
4040
+ },
4041
+ clearAllMocks() {
4042
+ [...mocks].reverse().forEach((spy) => spy.mockClear());
4043
+ return utils;
4044
+ },
4045
+ resetAllMocks() {
4046
+ [...mocks].reverse().forEach((spy) => spy.mockReset());
4047
+ return utils;
4048
+ },
4049
+ restoreAllMocks() {
4050
+ [...mocks].reverse().forEach((spy) => spy.mockRestore());
4051
+ return utils;
4052
+ },
4053
+ stubGlobal(name, value) {
4054
+ if (!_stubsGlobal.has(name)) {
4055
+ _stubsGlobal.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
4056
+ }
4057
+ Object.defineProperty(globalThis, name, {
4058
+ value,
4059
+ writable: true,
4060
+ configurable: true,
4061
+ enumerable: true
4062
+ });
4063
+ return utils;
4064
+ },
4065
+ stubEnv(name, value) {
4066
+ if (!_stubsEnv.has(name)) {
4067
+ _stubsEnv.set(name, process.env[name]);
4068
+ }
4069
+ if (_envBooleans.includes(name)) {
4070
+ process.env[name] = value ? "1" : "";
4071
+ } else if (value === undefined) {
4072
+ delete process.env[name];
4073
+ } else {
4074
+ process.env[name] = String(value);
4075
+ }
4076
+ return utils;
4077
+ },
4078
+ unstubAllGlobals() {
4079
+ _stubsGlobal.forEach((original, name) => {
4080
+ if (!original) {
4081
+ Reflect.deleteProperty(globalThis, name);
4082
+ } else {
4083
+ Object.defineProperty(globalThis, name, original);
4084
+ }
4085
+ });
4086
+ _stubsGlobal.clear();
4087
+ return utils;
4088
+ },
4089
+ unstubAllEnvs() {
4090
+ _stubsEnv.forEach((original, name) => {
4091
+ if (original === undefined) {
4092
+ delete process.env[name];
4093
+ } else {
4094
+ process.env[name] = original;
4095
+ }
4096
+ });
4097
+ _stubsEnv.clear();
4098
+ return utils;
4099
+ },
4100
+ resetModules() {
4101
+ resetModules(workerState.moduleCache);
4102
+ return utils;
4103
+ },
4104
+ async dynamicImportSettled() {
4105
+ return waitForImportsToResolve();
4106
+ },
4107
+ setConfig(config) {
4108
+ if (!_config) {
4109
+ _config = { ...workerState.config };
4110
+ }
4111
+ Object.assign(workerState.config, config);
4112
+ },
4113
+ resetConfig() {
4114
+ if (_config) {
4115
+ Object.assign(workerState.config, _config);
4116
+ }
4117
+ }
4118
+ };
4119
+ return utils;
4254
4120
  }
4255
4121
  const vitest = createVitest();
4256
4122
  const vi = vitest;
4257
4123
  function _mocker() {
4258
- return typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : new Proxy(
4259
- {},
4260
- {
4261
- get(_, name) {
4262
- throw new Error(
4263
- `Vitest mocker was not initialized in this environment. vi.${String(name)}() is forbidden.`
4264
- );
4265
- }
4266
- }
4267
- );
4124
+ return typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : new Proxy({}, { get(_, name) {
4125
+ throw new Error("Vitest mocker was not initialized in this environment. " + `vi.${String(name)}() is forbidden.`);
4126
+ } });
4268
4127
  }
4269
4128
  function getImporter(name) {
4270
- const stackTrace = createSimpleStackTrace({ stackTraceLimit: 5 });
4271
- const stackArray = stackTrace.split("\n");
4272
- const importerStackIndex = stackArray.findIndex((stack2) => {
4273
- return stack2.includes(` at Object.${name}`) || stack2.includes(`${name}@`);
4274
- });
4275
- const stack = parseSingleStack(stackArray[importerStackIndex + 1]);
4276
- return stack?.file || "";
4129
+ const stackTrace = createSimpleStackTrace({ stackTraceLimit: 5 });
4130
+ const stackArray = stackTrace.split("\n");
4131
+ const importerStackIndex = stackArray.findIndex((stack) => {
4132
+ return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`);
4133
+ });
4134
+ const stack = parseSingleStack(stackArray[importerStackIndex + 1]);
4135
+ return stack?.file || "";
4277
4136
  }
4278
4137
 
4279
4138
  export { globalExpect as a, vitest as b, createExpect as c, getSnapshotClient as g, inject as i, vi as v };