vitest 4.1.12 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/LICENSE.md +192 -10
  2. package/browser/context.d.ts +7 -1
  3. package/browser/context.js +5 -5
  4. package/config.d.ts +0 -2
  5. package/dist/browser.d.ts +52 -21
  6. package/dist/browser.js +12 -13
  7. package/dist/chunks/{acorn.B2iPLyUM.js → acorn.C1kjbUFw.js} +30 -30
  8. package/dist/chunks/{base.B6Opl8PE.js → base.Cof-UHJf.js} +81 -52
  9. package/dist/chunks/{browser.d.BcoexmFG.d.ts → browser.d.C7tWgUvw.d.ts} +17 -14
  10. package/dist/chunks/{cac.DzDtg8hz.js → cac.BYbt0aJp.js} +143 -87
  11. package/dist/chunks/{cli-api.B0Pz1_R7.js → cli-api.COfZo8lK.js} +7160 -7189
  12. package/dist/chunks/config.d.B3YV4t0O.d.ts +3873 -0
  13. package/dist/chunks/{console.3WNpx0tS.js → console.CQZ877Hi.js} +69 -63
  14. package/dist/chunks/{constants.CPYnjOGj.js → constants.DLYM6cZY.js} +2 -2
  15. package/dist/chunks/coverage.9iqXE2gN.js +26 -0
  16. package/dist/chunks/{coverage.CTzCuANN.js → coverage.jGCktcGP.js} +7 -2
  17. package/dist/chunks/{creator.DgVhQm5q.js → creator.DHWmytIK.js} +65 -28
  18. package/dist/chunks/{defaults.9aQKnqFk.js → defaults.B1FCaFfh.js} +16 -9
  19. package/dist/chunks/display.BlTmubjj.js +194 -0
  20. package/dist/chunks/doctor.B-oPbwps.js +465 -0
  21. package/dist/chunks/{env.D4Lgay0q.js → env.BKKtU2WC.js} +2 -1
  22. package/dist/chunks/{environment.d.CrsxCzP1.d.ts → environment.d.BFQtFKdZ.d.ts} +9 -1
  23. package/dist/chunks/globals.ZKtKSkEf.js +29 -0
  24. package/dist/chunks/index.Bi0NXYPf.js +1708 -0
  25. package/dist/chunks/{index.CMESou6r.js → index.BoyTG_B7.js} +82 -81
  26. package/dist/chunks/index.CZzC1gGg.js +8501 -0
  27. package/dist/chunks/index.D0heQG4v.js +1318 -0
  28. package/dist/chunks/index.Di8au7q4.js +15665 -0
  29. package/dist/chunks/{index.Chj8NDwU.js → index.DmDMHCg8.js} +6 -12
  30. package/dist/chunks/{index.DXx9Dtk7.js → index.w_oBZ9N8.js} +25 -12
  31. package/dist/chunks/{init-forks.H5ZuobOQ.js → init-forks.BaDXQSD8.js} +7 -10
  32. package/dist/chunks/{init-threads.6kl1khcL.js → init-threads.ZX_Vov0z.js} +1 -1
  33. package/dist/chunks/{init.k9zZ9sLh.js → init.CO4AB7HZ.js} +113 -38
  34. package/dist/chunks/module-dependencies._2Eei3FO.js +71 -0
  35. package/dist/chunks/{native.DPzPHdi5.js → native.upB-V0CK.js} +50 -37
  36. package/dist/chunks/{nativeModuleMocker.BkNfQMkH.js → nativeModuleMocker.Dh5azSB4.js} +48 -19
  37. package/dist/chunks/{index.BCY_7LL2.js → nativeModuleRunner.9xPIMzi7.js} +110 -42
  38. package/dist/chunks/node.B9mkVmLH.js +47 -0
  39. package/dist/chunks/offset.Dy-5Fdfn.js +24 -0
  40. package/dist/chunks/pathe.M-eThtNZ.zq3TM4NT.js +492 -0
  41. package/dist/chunks/{reporters.d.DtoKVV2s.d.ts → plugin.d.LRFSN46m.d.ts} +2573 -1453
  42. package/dist/chunks/plugins.DPQHVT0p.js +37 -0
  43. package/dist/chunks/rawSnapshot.DqSiqIEx.js +356 -0
  44. package/dist/chunks/resolver.BzpmeQeT.js +48 -0
  45. package/dist/chunks/rpc.Uhkwr2NM.js +93 -0
  46. package/dist/chunks/rpc.d.3FOhdFx8.d.ts +75 -0
  47. package/dist/chunks/run.CjdgFZiW.js +4231 -0
  48. package/dist/chunks/setup-common.CqAQCXzx.js +36 -0
  49. package/dist/chunks/source-map.DakdQc29.js +1788 -0
  50. package/dist/chunks/source-map.d.BkG8YK_3.d.ts +89 -0
  51. package/dist/chunks/spy.DDMXghXv.js +509 -0
  52. package/dist/chunks/task-utils.d.D-gFPNFi.d.ts +144 -0
  53. package/dist/chunks/tinyrainbow.Do8I1XRG.js +88 -0
  54. package/dist/chunks/{utils.BS4fH3nR.js → utils.BBk_icFG.js} +50 -52
  55. package/dist/chunks/{utils.BX5Fg8C4.js → utils.DYj33du9.js} +1 -17
  56. package/dist/chunks/vm.b4MbCAJQ.js +1329 -0
  57. package/dist/chunks/{worker.d.ZpHpO4yb.d.ts → worker.d.CyJRpyfZ.d.ts} +34 -19
  58. package/dist/cli.js +5 -6
  59. package/dist/config.cjs +9 -6
  60. package/dist/config.d.ts +27 -25
  61. package/dist/config.js +3 -3
  62. package/dist/index.d.ts +471 -38
  63. package/dist/index.js +18 -19
  64. package/dist/module-evaluator.d.ts +64 -5
  65. package/dist/module-evaluator.js +122 -62
  66. package/dist/node.d.ts +355 -87
  67. package/dist/node.js +49 -73
  68. package/dist/runtime.d.ts +43 -6
  69. package/dist/runtime.js +7 -9
  70. package/dist/spy.js +1 -1
  71. package/dist/task-utils.js +290 -0
  72. package/dist/{chunks/traces.DT5aQ62U.js → traces.js} +3 -2
  73. package/dist/worker.d.ts +8 -10
  74. package/dist/worker.js +33 -43
  75. package/dist/workers/forks.js +30 -40
  76. package/dist/workers/runVmTests.js +66 -43
  77. package/dist/workers/threads.js +30 -40
  78. package/dist/workers/vmForks.js +19 -20
  79. package/dist/workers/vmThreads.js +19 -20
  80. package/globals.d.ts +19 -19
  81. package/index.cjs +3 -3
  82. package/optional-runtime-types.d.ts +1 -1
  83. package/optional-types.d.ts +1 -1
  84. package/package.json +59 -74
  85. package/suppress-warnings.cjs +1 -1
  86. package/dist/chunks/_commonjsHelpers.D26ty3Ew.js +0 -6
  87. package/dist/chunks/benchmark.CX_oY03V.js +0 -40
  88. package/dist/chunks/benchmark.d.DAaHLpsq.d.ts +0 -24
  89. package/dist/chunks/config.d.A1h_Y6Jt.d.ts +0 -232
  90. package/dist/chunks/coverage.DM_a_rWm.js +0 -1087
  91. package/dist/chunks/coverage.d.BZtK59WP.d.ts +0 -37
  92. package/dist/chunks/evaluatedModules.Dg1zASAC.js +0 -17
  93. package/dist/chunks/global.d.DVsSRdQ5.d.ts +0 -100
  94. package/dist/chunks/globals.Dj1TGiMC.js +0 -31
  95. package/dist/chunks/index.DC7d2Pf8.js +0 -729
  96. package/dist/chunks/index.DdgEv5B1.js +0 -42
  97. package/dist/chunks/index.UpGiHP7g.js +0 -4255
  98. package/dist/chunks/index.og1WyBLx.js +0 -6358
  99. package/dist/chunks/nativeModuleRunner.BIakptoF.js +0 -36
  100. package/dist/chunks/node.COQbm6gK.js +0 -14
  101. package/dist/chunks/plugin.d.DwFIiJ7i.d.ts +0 -38
  102. package/dist/chunks/rpc.MzXet3jl.js +0 -144
  103. package/dist/chunks/rpc.d.B_8sPU0w.d.ts +0 -30
  104. package/dist/chunks/setup-common.DYx3LtFI.js +0 -60
  105. package/dist/chunks/startVitestModuleRunner.DB-7oCpn.js +0 -740
  106. package/dist/chunks/suite.d.udJtyAgw.d.ts +0 -10
  107. package/dist/chunks/test.DNmyFkvJ.js +0 -4430
  108. package/dist/chunks/traces.d.D2T_R8rx.d.ts +0 -60
  109. package/dist/chunks/vm.CXMd5FHa.js +0 -785
  110. package/dist/coverage.d.ts +0 -123
  111. package/dist/coverage.js +0 -27
  112. package/dist/environments.d.ts +0 -22
  113. package/dist/environments.js +0 -5
  114. package/dist/reporters.d.ts +0 -27
  115. package/dist/reporters.js +0 -26
  116. package/dist/runners.d.ts +0 -70
  117. package/dist/runners.js +0 -19
  118. package/dist/snapshot.d.ts +0 -9
  119. package/dist/snapshot.js +0 -6
  120. package/dist/suite.d.ts +0 -5
  121. package/dist/suite.js +0 -8
@@ -0,0 +1,89 @@
1
+ import { T as TestError, P as ParsedStack } from './config.d.B3YV4t0O.js';
2
+
3
+ interface RuntimeCoverageModuleLoader {
4
+ import: (id: string) => Promise<{
5
+ default: RuntimeCoverageProviderModule;
6
+ }>;
7
+ isBrowser?: boolean;
8
+ moduleExecutionInfo?: Map<string, {
9
+ startOffset: number;
10
+ }>;
11
+ }
12
+ interface RuntimeCoverageProviderModule {
13
+ /**
14
+ * Factory for creating a new coverage provider
15
+ */
16
+ getProvider: () => any;
17
+ /**
18
+ * Executed before tests are run in the worker thread.
19
+ */
20
+ startCoverage?: (runtimeOptions: {
21
+ isolate: boolean;
22
+ /** @internal */
23
+ autoAttachSubprocess: boolean;
24
+ /** @internal */
25
+ reportsDirectory: string;
26
+ }) => unknown | Promise<unknown>;
27
+ /**
28
+ * Executed on after each run in the worker thread. Possible to return a payload passed to the provider
29
+ */
30
+ takeCoverage?: (runtimeOptions?: {
31
+ moduleExecutionInfo?: Map<string, {
32
+ startOffset: number;
33
+ }>;
34
+ coverageFilesDirectory: string;
35
+ }) => unknown | Promise<unknown>;
36
+ /**
37
+ * Executed after all tests have been run in the worker thread.
38
+ */
39
+ stopCoverage?: (runtimeOptions: {
40
+ isolate: boolean;
41
+ }) => unknown | Promise<unknown>;
42
+ }
43
+
44
+ type OriginalMapping = {
45
+ source: string | null;
46
+ line: number;
47
+ column: number;
48
+ name: string | null;
49
+ };
50
+
51
+ interface StackTraceParserOptions {
52
+ ignoreStackEntries?: (RegExp | string)[];
53
+ getSourceMap?: (file: string) => unknown;
54
+ getUrlId?: (id: string) => string;
55
+ frameFilter?: (error: TestError, frame: ParsedStack) => boolean | void;
56
+ firstOnly?: boolean;
57
+ }
58
+ interface SourceMapLike {
59
+ version: number;
60
+ mappings?: string;
61
+ names?: string[];
62
+ sources?: string[];
63
+ sourcesContent?: string[];
64
+ sourceRoot?: string;
65
+ }
66
+ interface Needle {
67
+ line: number;
68
+ column: number;
69
+ }
70
+ declare class DecodedMap {
71
+ map: SourceMapLike;
72
+ _encoded: string;
73
+ _decoded: undefined | number[][][];
74
+ _decodedMemo: Stats;
75
+ url: string;
76
+ version: number;
77
+ names: string[];
78
+ resolvedSources: string[];
79
+ constructor(map: SourceMapLike, from: string);
80
+ }
81
+ interface Stats {
82
+ lastKey: number;
83
+ lastNeedle: number;
84
+ lastIndex: number;
85
+ }
86
+ declare function getOriginalPosition(map: DecodedMap, needle: Needle): OriginalMapping | null;
87
+
88
+ export { DecodedMap as D, getOriginalPosition as g };
89
+ export type { RuntimeCoverageModuleLoader as R, StackTraceParserOptions as S, RuntimeCoverageProviderModule as a };
@@ -0,0 +1,509 @@
1
+ function isMockFunction(fn) {
2
+ return typeof fn === "function" && "_isMockFunction" in fn && fn._isMockFunction === true;
3
+ }
4
+ const MOCK_RESTORE = /* @__PURE__ */ new Set();
5
+ // Jest keeps the state in a separate WeakMap which is good for memory,
6
+ // but it makes the state slower to access and return different values
7
+ // if you stored it before calling `mockClear` where it will be recreated
8
+ const DIRTY_MOCK_STATES = /* @__PURE__ */ new Set();
9
+ // Mocks whose implementation, once-queue or name changed since their last
10
+ // `mockReset()`, so `resetAllMocks()` only visits mocks that are not already reset
11
+ const DIRTY_MOCK_CONFIGS = /* @__PURE__ */ new Set();
12
+ // a test may spy on `Set.prototype.add`, and the spy itself marks mocks dirty
13
+ const addToSet = Set.prototype.add;
14
+ const MOCK_REFS = /* @__PURE__ */ new WeakMap();
15
+ const MOCK_FINALIZER = new FinalizationRegistry((ref) => {
16
+ DIRTY_MOCK_STATES.delete(ref);
17
+ DIRTY_MOCK_CONFIGS.delete(ref);
18
+ });
19
+ const MOCK_CONFIGS = /* @__PURE__ */ new WeakMap();
20
+ const MOCKS_BY_STATE = /* @__PURE__ */ new WeakMap();
21
+ function markDirty(set, mock) {
22
+ let ref = MOCK_REFS.get(mock);
23
+ if (!ref) {
24
+ ref = new WeakRef(mock);
25
+ MOCK_REFS.set(mock, ref);
26
+ MOCK_FINALIZER.register(mock, ref);
27
+ }
28
+ addToSet.call(set, ref);
29
+ }
30
+ function unmarkDirty(set, mock) {
31
+ const ref = MOCK_REFS.get(mock);
32
+ if (ref) set.delete(ref);
33
+ }
34
+ function forEachDirty(set, fn) {
35
+ for (const ref of set) {
36
+ const mock = ref.deref();
37
+ if (mock) fn(mock);
38
+ else set.delete(ref);
39
+ }
40
+ }
41
+ function createMockInstance(options = {}) {
42
+ const { originalImplementation, restore, mockImplementation, resetToMockImplementation, resetToMockName } = options;
43
+ if (restore) MOCK_RESTORE.add(restore);
44
+ const config = getDefaultConfig(originalImplementation);
45
+ const state = getDefaultState();
46
+ const mock = createMock({
47
+ config,
48
+ state,
49
+ ...options
50
+ });
51
+ const mockLength = (mockImplementation || originalImplementation)?.length ?? 0;
52
+ Object.defineProperty(mock, "length", {
53
+ writable: true,
54
+ enumerable: false,
55
+ value: mockLength,
56
+ configurable: true
57
+ });
58
+ // inherit the default name so it appears in snapshots and logs
59
+ // this is used by `vi.spyOn()` for better debugging.
60
+ // when `vi.fn()` is called, we just use the default string
61
+ if (resetToMockName) config.mockName = mock.name || "vi.fn()";
62
+ MOCK_CONFIGS.set(mock, config);
63
+ MOCKS_BY_STATE.set(state, mock);
64
+ mock._isMockFunction = true;
65
+ mock.getMockImplementation = () => {
66
+ // Jest only returns `config.mockImplementation` here,
67
+ // but we think it makes sense to return what the next function will be called
68
+ return config.onceMockImplementations[0] || config.mockImplementation;
69
+ };
70
+ // keep the prototype chain in sync with the implementation the next
71
+ // construction will use, so it is correct before any `new` call.
72
+ // automocked classes are skipped: their methods are pre-mocked
73
+ // on `mock.prototype`
74
+ const updateMockPrototype = () => {
75
+ if (!options.prototypeMembers?.length) reparentMockPrototype(mock, config.onceMockImplementations[0] || config.mockImplementation || originalImplementation);
76
+ };
77
+ Object.defineProperty(mock, "mock", {
78
+ configurable: false,
79
+ enumerable: true,
80
+ writable: false,
81
+ value: state
82
+ });
83
+ mock.mockImplementation = function mockImplementation(implementation) {
84
+ markDirty(DIRTY_MOCK_CONFIGS, mock);
85
+ config.mockImplementation = implementation;
86
+ updateMockPrototype();
87
+ return mock;
88
+ };
89
+ mock.mockImplementationOnce = function mockImplementationOnce(implementation) {
90
+ markDirty(DIRTY_MOCK_CONFIGS, mock);
91
+ config.onceMockImplementations.push(implementation);
92
+ updateMockPrototype();
93
+ return mock;
94
+ };
95
+ mock.withImplementation = function withImplementation(implementation, callback) {
96
+ markDirty(DIRTY_MOCK_CONFIGS, mock);
97
+ const previousImplementation = config.mockImplementation;
98
+ const previousOnceImplementations = config.onceMockImplementations;
99
+ const reset = () => {
100
+ config.mockImplementation = previousImplementation;
101
+ config.onceMockImplementations = previousOnceImplementations;
102
+ markDirty(DIRTY_MOCK_CONFIGS, mock);
103
+ updateMockPrototype();
104
+ };
105
+ config.mockImplementation = implementation;
106
+ config.onceMockImplementations = [];
107
+ updateMockPrototype();
108
+ const returnValue = callback();
109
+ if (typeof returnValue === "object" && typeof returnValue?.then === "function") return returnValue.then(() => {
110
+ reset();
111
+ return mock;
112
+ });
113
+ else reset();
114
+ return mock;
115
+ };
116
+ mock.mockReturnThis = function mockReturnThis() {
117
+ return mock.mockImplementation(function() {
118
+ return this;
119
+ });
120
+ };
121
+ mock.mockReturnValue = function mockReturnValue(value) {
122
+ return mock.mockImplementation(function() {
123
+ if (new.target) throwConstructorError("mockReturnValue");
124
+ return value;
125
+ });
126
+ };
127
+ mock.mockReturnValueOnce = function mockReturnValueOnce(value) {
128
+ return mock.mockImplementationOnce(function() {
129
+ if (new.target) throwConstructorError("mockReturnValueOnce");
130
+ return value;
131
+ });
132
+ };
133
+ mock.mockThrow = function mockThrow(value) {
134
+ // oxlint-disable-next-line prefer-arrow-callback
135
+ return mock.mockImplementation(function() {
136
+ throw value;
137
+ });
138
+ };
139
+ mock.mockThrowOnce = function mockThrowOnce(value) {
140
+ // oxlint-disable-next-line prefer-arrow-callback
141
+ return mock.mockImplementationOnce(function() {
142
+ throw value;
143
+ });
144
+ };
145
+ mock.mockResolvedValue = function mockResolvedValue(value) {
146
+ return mock.mockImplementation(function() {
147
+ if (new.target) throwConstructorError("mockResolvedValue");
148
+ return Promise.resolve(value);
149
+ });
150
+ };
151
+ mock.mockResolvedValueOnce = function mockResolvedValueOnce(value) {
152
+ return mock.mockImplementationOnce(function() {
153
+ if (new.target) throwConstructorError("mockResolvedValueOnce");
154
+ return Promise.resolve(value);
155
+ });
156
+ };
157
+ mock.mockRejectedValue = function mockRejectedValue(value) {
158
+ return mock.mockImplementation(function() {
159
+ if (new.target) throwConstructorError("mockRejectedValue");
160
+ return Promise.reject(value);
161
+ });
162
+ };
163
+ mock.mockRejectedValueOnce = function mockRejectedValueOnce(value) {
164
+ return mock.mockImplementationOnce(function() {
165
+ if (new.target) throwConstructorError("mockRejectedValueOnce");
166
+ return Promise.reject(value);
167
+ });
168
+ };
169
+ mock.mockClear = function mockClear() {
170
+ state.calls = [];
171
+ state.contexts = [];
172
+ state.instances = [];
173
+ state.invocationCallOrder = [];
174
+ state.results = [];
175
+ state.settledResults = [];
176
+ unmarkDirty(DIRTY_MOCK_STATES, mock);
177
+ return mock;
178
+ };
179
+ mock.mockReset = function mockReset() {
180
+ mock.mockClear();
181
+ config.mockImplementation = resetToMockImplementation ? mockImplementation : void 0;
182
+ config.mockName = resetToMockName ? mock.name || "vi.fn()" : "vi.fn()";
183
+ config.onceMockImplementations = [];
184
+ unmarkDirty(DIRTY_MOCK_CONFIGS, mock);
185
+ updateMockPrototype();
186
+ return mock;
187
+ };
188
+ mock.mockRestore = function mockRestore() {
189
+ mock.mockReset();
190
+ return restore?.();
191
+ };
192
+ mock.mockName = function mockName(name) {
193
+ if (typeof name === "string") {
194
+ markDirty(DIRTY_MOCK_CONFIGS, mock);
195
+ config.mockName = name;
196
+ }
197
+ return mock;
198
+ };
199
+ mock.getMockName = function getMockName() {
200
+ return config.mockName || "vi.fn()";
201
+ };
202
+ if (Symbol.dispose) mock[Symbol.dispose] = () => mock.mockRestore();
203
+ if (mockImplementation) mock.mockImplementation(mockImplementation);
204
+ else
205
+ // vi.spyOn() has no mock implementation, chain the original one
206
+ updateMockPrototype();
207
+ return mock;
208
+ }
209
+ function fn(originalImplementation) {
210
+ // if the function is already a mock, just return the same function,
211
+ // similarly to how vi.spyOn() works
212
+ if (originalImplementation != null && isMockFunction(originalImplementation)) return originalImplementation;
213
+ return createMockInstance({
214
+ // we pass this down so getMockImplementation() always returns the value
215
+ mockImplementation: originalImplementation,
216
+ // special case so that .mockReset() resets the value to
217
+ // the the originalImplementation instead of () => undefined
218
+ resetToMockImplementation: true
219
+ });
220
+ }
221
+ function spyOn(object, key, accessor) {
222
+ assert(object != null, "The vi.spyOn() function could not find an object to spy upon. The first argument must be defined.");
223
+ assert(typeof object === "object" || typeof object === "function", "Vitest cannot spy on a primitive value.");
224
+ const [originalDescriptorObject, originalDescriptor] = getDescriptor(object, key) || [];
225
+ assert(originalDescriptor || key in object, `The property "${String(key)}" is not defined on the ${typeof object}.`);
226
+ let accessType = accessor || "value";
227
+ let ssr = false;
228
+ // vite ssr support - actual function is stored inside a getter
229
+ if (accessType === "value" && originalDescriptor && originalDescriptor.value == null && originalDescriptor.get) {
230
+ accessType = "get";
231
+ ssr = true;
232
+ }
233
+ let original;
234
+ if (originalDescriptor) {
235
+ original = originalDescriptor[accessType];
236
+ // weird Proxy edge case where descriptor's value is undefined,
237
+ // but there's still a value on the object when called
238
+ // https://github.com/vitest-dev/vitest/issues/9439
239
+ if (original == null && accessType === "value") original = object[key];
240
+ } else if (accessType !== "value") original = () => object[key];
241
+ else original = object[key];
242
+ const originalImplementation = ssr && original ? original() : original;
243
+ const originalType = typeof originalImplementation;
244
+ assert(
245
+ // allow only functions
246
+ originalType === "function" || accessType !== "value" && original == null,
247
+ `vi.spyOn() can only spy on a function. Received ${originalType}.`
248
+ );
249
+ if (isMockFunction(originalImplementation)) return originalImplementation;
250
+ const reassign = (cb) => {
251
+ const { value, ...desc } = originalDescriptor || {
252
+ configurable: true,
253
+ writable: true
254
+ };
255
+ if (accessType !== "value") delete desc.writable;
256
+ desc[accessType] = cb;
257
+ Object.defineProperty(object, key, desc);
258
+ };
259
+ const restore = () => {
260
+ // if method is defined on the prototype, we can just remove it from
261
+ // the current object instead of redefining a copy of it
262
+ if (originalDescriptorObject !== object) Reflect.deleteProperty(object, key);
263
+ else if (originalDescriptor && !original) Object.defineProperty(object, key, originalDescriptor);
264
+ else reassign(original);
265
+ };
266
+ const mock = createMockInstance({
267
+ restore,
268
+ originalImplementation,
269
+ resetToMockName: true
270
+ });
271
+ try {
272
+ reassign(ssr ? () => mock : mock);
273
+ } catch (error) {
274
+ if (error instanceof TypeError && Symbol.toStringTag && object[Symbol.toStringTag] === "Module" && (error.message.includes("Cannot redefine property") || error.message.includes("Cannot replace module namespace") || error.message.includes("can't redefine non-configurable property"))) throw new TypeError(`Cannot spy on export "${String(key)}". Module namespace is not configurable in ESM. See: https://vitest.dev/guide/mocking/modules#mocking-a-module`, { cause: error });
275
+ throw error;
276
+ }
277
+ return mock;
278
+ }
279
+ function getDescriptor(obj, method) {
280
+ const objDescriptor = Object.getOwnPropertyDescriptor(obj, method);
281
+ if (objDescriptor) return [obj, objDescriptor];
282
+ let currentProto = Object.getPrototypeOf(obj);
283
+ while (currentProto !== null) {
284
+ const descriptor = Object.getOwnPropertyDescriptor(currentProto, method);
285
+ if (descriptor) return [currentProto, descriptor];
286
+ currentProto = Object.getPrototypeOf(currentProto);
287
+ }
288
+ }
289
+ function assert(condition, message) {
290
+ if (!condition) throw new Error(message);
291
+ }
292
+ let invocationCallCounter = 1;
293
+ function createMock({ state, config, name: mockName, prototypeState, prototypeConfig, keepMembersImplementation, mockImplementation, prototypeMembers = [] }) {
294
+ const original = config.mockOriginal;
295
+ const pseudoOriginal = mockImplementation;
296
+ const name = mockName || original?.name || "Mock";
297
+ const noopImplementation = function() {};
298
+ const prototypeMock = prototypeState && MOCKS_BY_STATE.get(prototypeState);
299
+ const namedObject = {
300
+ // to keep the name of the function intact
301
+ [name]: function(...args) {
302
+ markDirty(DIRTY_MOCK_STATES, namedObject[name]);
303
+ if (prototypeMock) markDirty(DIRTY_MOCK_STATES, prototypeMock);
304
+ registerCalls(args, state, prototypeState);
305
+ registerInvocationOrder(invocationCallCounter++, state, prototypeState);
306
+ const result = {
307
+ type: "incomplete",
308
+ value: void 0
309
+ };
310
+ const settledResult = {
311
+ type: "incomplete",
312
+ value: void 0
313
+ };
314
+ registerResult(result, state, prototypeState);
315
+ registerSettledResult(settledResult, state, prototypeState);
316
+ const context = new.target ? void 0 : this;
317
+ const [instanceIndex, instancePrototypeIndex] = registerInstance(context, state, prototypeState);
318
+ const [contextIndex, contextPrototypeIndex] = registerContext(context, state, prototypeState);
319
+ const implementation = config.onceMockImplementations.shift() || config.mockImplementation || prototypeConfig?.onceMockImplementations.shift() || prototypeConfig?.mockImplementation || original || noopImplementation;
320
+ let returnValue;
321
+ let thrownValue;
322
+ let didThrow = false;
323
+ try {
324
+ if (new.target) {
325
+ // the prototype chain is already prepared when the implementation
326
+ // is registered, but a consumed `mockImplementationOnce` can change
327
+ // which implementation this construction uses
328
+ if (prototypeMembers.length === 0) reparentMockPrototype(
329
+ // oxlint-disable-next-line typescript/no-use-before-define
330
+ mock,
331
+ implementation === noopImplementation ? void 0 : implementation
332
+ );
333
+ returnValue = Reflect.construct(implementation, args, new.target);
334
+ // jest calls this before the implementation, but we have to resolve this _after_
335
+ // because we cannot do it before the `Reflect.construct` called the custom implementation.
336
+ // fortunately, the constructor is always an empty function because `prototypeMethods`
337
+ // are only used by the automocker, so this doesn't matter
338
+ for (const prop of prototypeMembers) {
339
+ const prototypeMock = returnValue[prop];
340
+ // the method was overridden because of inheritance, ignore it
341
+ // oxlint-disable-next-line typescript/no-use-before-define
342
+ if (prototypeMock !== mock.prototype[prop]) continue;
343
+ const isMock = isMockFunction(prototypeMock);
344
+ const prototypeState = isMock ? prototypeMock.mock : void 0;
345
+ const prototypeConfig = isMock ? MOCK_CONFIGS.get(prototypeMock) : void 0;
346
+ returnValue[prop] = createMockInstance({
347
+ originalImplementation: keepMembersImplementation ? prototypeConfig?.mockOriginal : void 0,
348
+ prototypeState,
349
+ prototypeConfig,
350
+ keepMembersImplementation
351
+ });
352
+ }
353
+ } else returnValue = implementation.apply(this, args);
354
+ } catch (error) {
355
+ thrownValue = error;
356
+ didThrow = true;
357
+ if (error instanceof TypeError && error.message.includes("is not a constructor")) console.warn(`[vitest] The ${namedObject[name].getMockName()} mock did not use 'function' or 'class' in its implementation, see https://vitest.dev/api/vi#vi-spyon for examples.`);
358
+ throw error;
359
+ } finally {
360
+ if (didThrow) {
361
+ result.type = "throw";
362
+ result.value = thrownValue;
363
+ settledResult.type = "rejected";
364
+ settledResult.value = thrownValue;
365
+ } else {
366
+ result.type = "return";
367
+ result.value = returnValue;
368
+ if (new.target) {
369
+ state.contexts[contextIndex - 1] = returnValue;
370
+ state.instances[instanceIndex - 1] = returnValue;
371
+ if (contextPrototypeIndex != null && prototypeState) prototypeState.contexts[contextPrototypeIndex - 1] = returnValue;
372
+ if (instancePrototypeIndex != null && prototypeState) prototypeState.instances[instancePrototypeIndex - 1] = returnValue;
373
+ }
374
+ if (returnValue instanceof Promise) returnValue.then((settledValue) => {
375
+ settledResult.type = "fulfilled";
376
+ settledResult.value = settledValue;
377
+ }, (rejectedValue) => {
378
+ settledResult.type = "rejected";
379
+ settledResult.value = rejectedValue;
380
+ });
381
+ else {
382
+ settledResult.type = "fulfilled";
383
+ settledResult.value = returnValue;
384
+ }
385
+ }
386
+ }
387
+ return returnValue;
388
+ } };
389
+ const mock = namedObject[name];
390
+ const copyPropertiesFrom = original || pseudoOriginal;
391
+ if (copyPropertiesFrom) copyOriginalStaticProperties(mock, copyPropertiesFrom);
392
+ return mock;
393
+ }
394
+ // puts the implementation's prototype behind `mock.prototype` so instances
395
+ // see prototype methods both during and after construction, while properties
396
+ // assigned on `mock.prototype` still shadow them
397
+ function reparentMockPrototype(mock, implementation) {
398
+ const mockPrototype = mock.prototype;
399
+ if (mockPrototype == null) return;
400
+ // an implementation without a usable prototype (reset mock, arrow or bound
401
+ // function) reverts the chain to `Object.prototype`, the parent every mock
402
+ // is created with
403
+ const parent = implementation?.prototype ?? Object.prototype;
404
+ if (mockPrototype !== parent && Object.getPrototypeOf(mockPrototype) !== parent) Object.setPrototypeOf(mockPrototype, parent);
405
+ }
406
+ function registerCalls(args, state, prototypeState) {
407
+ state.calls.push(args);
408
+ prototypeState?.calls.push(args);
409
+ }
410
+ function registerInvocationOrder(order, state, prototypeState) {
411
+ state.invocationCallOrder.push(order);
412
+ prototypeState?.invocationCallOrder.push(order);
413
+ }
414
+ function registerResult(result, state, prototypeState) {
415
+ state.results.push(result);
416
+ prototypeState?.results.push(result);
417
+ }
418
+ function registerSettledResult(result, state, prototypeState) {
419
+ state.settledResults.push(result);
420
+ prototypeState?.settledResults.push(result);
421
+ }
422
+ function registerInstance(instance, state, prototypeState) {
423
+ return [state.instances.push(instance), prototypeState?.instances.push(instance)];
424
+ }
425
+ function registerContext(context, state, prototypeState) {
426
+ return [state.contexts.push(context), prototypeState?.contexts.push(context)];
427
+ }
428
+ function copyOriginalStaticProperties(mock, original) {
429
+ const { properties, descriptors } = getAllProperties(original);
430
+ for (const key of properties) {
431
+ const descriptor = descriptors[key];
432
+ if (getDescriptor(mock, key)) continue;
433
+ Object.defineProperty(mock, key, descriptor);
434
+ }
435
+ }
436
+ const ignoreProperties = /* @__PURE__ */ new Set([
437
+ "length",
438
+ "name",
439
+ "prototype",
440
+ Symbol.for("nodejs.util.promisify.custom")
441
+ ]);
442
+ function getAllProperties(original) {
443
+ const properties = /* @__PURE__ */ new Set();
444
+ const descriptors = {};
445
+ while (original && original !== Object.prototype && original !== Function.prototype) {
446
+ const ownProperties = [...Object.getOwnPropertyNames(original), ...Object.getOwnPropertySymbols(original)];
447
+ for (const prop of ownProperties) {
448
+ if (descriptors[prop] || ignoreProperties.has(prop)) continue;
449
+ properties.add(prop);
450
+ descriptors[prop] = Object.getOwnPropertyDescriptor(original, prop);
451
+ }
452
+ original = Object.getPrototypeOf(original);
453
+ }
454
+ return {
455
+ properties,
456
+ descriptors
457
+ };
458
+ }
459
+ function getDefaultConfig(original) {
460
+ return {
461
+ mockImplementation: void 0,
462
+ mockOriginal: original,
463
+ mockName: "vi.fn()",
464
+ onceMockImplementations: []
465
+ };
466
+ }
467
+ function getDefaultState() {
468
+ const state = {
469
+ calls: [],
470
+ contexts: [],
471
+ instances: [],
472
+ invocationCallOrder: [],
473
+ settledResults: [],
474
+ results: [],
475
+ get lastCall() {
476
+ return state.calls.at(-1);
477
+ }
478
+ };
479
+ return state;
480
+ }
481
+ function restoreAllMocks() {
482
+ for (const restore of MOCK_RESTORE) restore();
483
+ MOCK_RESTORE.clear();
484
+ }
485
+ function clearAllMocks() {
486
+ forEachDirty(DIRTY_MOCK_STATES, (mock) => mock.mockClear());
487
+ }
488
+ function resetAllMocks() {
489
+ // `mockReset()` removes the mock from both sets, so a mock present in both
490
+ // is visited once.
491
+ forEachDirty(DIRTY_MOCK_STATES, (mock) => mock.mockReset());
492
+ forEachDirty(DIRTY_MOCK_CONFIGS, (mock) => mock.mockReset());
493
+ }
494
+ function throwConstructorError(shorthand) {
495
+ throw new TypeError(`Cannot use \`${shorthand}\` when called with \`new\`. Use \`mockImplementation\` with a \`class\` keyword instead. See https://vitest.dev/api/mock#class-support for more information.`);
496
+ }
497
+
498
+ var spyModule = /*#__PURE__*/Object.freeze({
499
+ __proto__: null,
500
+ clearAllMocks: clearAllMocks,
501
+ createMockInstance: createMockInstance,
502
+ fn: fn,
503
+ isMockFunction: isMockFunction,
504
+ resetAllMocks: resetAllMocks,
505
+ restoreAllMocks: restoreAllMocks,
506
+ spyOn: spyOn
507
+ });
508
+
509
+ export { spyOn as a, resetAllMocks as b, clearAllMocks as c, createMockInstance as d, fn as f, isMockFunction as i, restoreAllMocks as r, spyModule as s };