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
@@ -1,4430 +0,0 @@
1
- import { getCurrentTest, updateTask, createTaskCollector, getCurrentSuite, getHooks, getFn } from '@vitest/runner';
2
- import { assertTypes, createSimpleStackTrace, createDefer } from '@vitest/utils/helpers';
3
- import { getSafeTimers, delay } from '@vitest/utils/timers';
4
- import { a as getBenchOptions, g as getBenchFn } from './benchmark.CX_oY03V.js';
5
- import { i as isChildProcess, w as waitForImportsToResolve, r as resetModules, g as getWorkerState } from './utils.BX5Fg8C4.js';
6
- import { chai, wrapAssertion, recordAsyncExpect, createAssertionMessage, equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, ChaiStyleAssertions, JestAsymmetricMatchers, GLOBAL_EXPECT, ASYMMETRIC_MATCHERS_OBJECT, getState, setState, addCustomEqualityTesters, customMatchers } from '@vitest/expect';
7
- import { getNames, getTests, getTestName, createChainable, matchesTags } from '@vitest/runner/utils';
8
- import { processError } from '@vitest/utils/error';
9
- import { normalize } from 'pathe';
10
- import { fn, spyOn, restoreAllMocks, resetAllMocks, clearAllMocks, isMockFunction } from '@vitest/spy';
11
- import '@vitest/utils/offset';
12
- import { parseSingleStack } from '@vitest/utils/source-map';
13
- import { c as commonjsGlobal } from './_commonjsHelpers.D26ty3Ew.js';
14
- import { R as RealDate, b as resetDate, m as mockDate, r as rpc } from './rpc.MzXet3jl.js';
15
- import { addSerializer, stripSnapshotIndentation, SnapshotClient } from '@vitest/snapshot';
16
-
17
- var fakeTimersSrc = {};
18
-
19
- var global;
20
- var hasRequiredGlobal;
21
-
22
- function requireGlobal () {
23
- if (hasRequiredGlobal) return global;
24
- hasRequiredGlobal = 1;
25
-
26
- /**
27
- * A reference to the global object
28
- * @type {object} globalObject
29
- */
30
- var globalObject;
31
-
32
- /* istanbul ignore else */
33
- if (typeof commonjsGlobal !== "undefined") {
34
- // Node
35
- globalObject = commonjsGlobal;
36
- } else if (typeof window !== "undefined") {
37
- // Browser
38
- globalObject = window;
39
- } else {
40
- // WebWorker
41
- globalObject = self;
42
- }
43
-
44
- global = globalObject;
45
- return global;
46
- }
47
-
48
- var throwsOnProto_1;
49
- var hasRequiredThrowsOnProto;
50
-
51
- function requireThrowsOnProto () {
52
- if (hasRequiredThrowsOnProto) return throwsOnProto_1;
53
- hasRequiredThrowsOnProto = 1;
54
-
55
- /**
56
- * Is true when the environment causes an error to be thrown for accessing the
57
- * __proto__ property.
58
- * This is necessary in order to support `node --disable-proto=throw`.
59
- *
60
- * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
61
- * @type {boolean}
62
- */
63
- let throwsOnProto;
64
- try {
65
- const object = {};
66
- // eslint-disable-next-line no-proto, no-unused-expressions
67
- object.__proto__;
68
- throwsOnProto = false;
69
- } catch (_) {
70
- // This branch is covered when tests are run with `--disable-proto=throw`,
71
- // however we can test both branches at the same time, so this is ignored
72
- /* istanbul ignore next */
73
- throwsOnProto = true;
74
- }
75
-
76
- throwsOnProto_1 = throwsOnProto;
77
- return throwsOnProto_1;
78
- }
79
-
80
- var copyPrototypeMethods;
81
- var hasRequiredCopyPrototypeMethods;
82
-
83
- function requireCopyPrototypeMethods () {
84
- if (hasRequiredCopyPrototypeMethods) return copyPrototypeMethods;
85
- hasRequiredCopyPrototypeMethods = 1;
86
-
87
- var call = Function.call;
88
- var throwsOnProto = requireThrowsOnProto();
89
-
90
- var disallowedProperties = [
91
- // ignore size because it throws from Map
92
- "size",
93
- "caller",
94
- "callee",
95
- "arguments",
96
- ];
97
-
98
- // This branch is covered when tests are run with `--disable-proto=throw`,
99
- // however we can test both branches at the same time, so this is ignored
100
- /* istanbul ignore next */
101
- if (throwsOnProto) {
102
- disallowedProperties.push("__proto__");
103
- }
104
-
105
- copyPrototypeMethods = function copyPrototypeMethods(prototype) {
106
- // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
107
- return Object.getOwnPropertyNames(prototype).reduce(function (
108
- result,
109
- name
110
- ) {
111
- if (disallowedProperties.includes(name)) {
112
- return result;
113
- }
114
-
115
- if (typeof prototype[name] !== "function") {
116
- return result;
117
- }
118
-
119
- result[name] = call.bind(prototype[name]);
120
-
121
- return result;
122
- },
123
- Object.create(null));
124
- };
125
- return copyPrototypeMethods;
126
- }
127
-
128
- var array;
129
- var hasRequiredArray;
130
-
131
- function requireArray () {
132
- if (hasRequiredArray) return array;
133
- hasRequiredArray = 1;
134
-
135
- var copyPrototype = requireCopyPrototypeMethods();
136
-
137
- array = copyPrototype(Array.prototype);
138
- return array;
139
- }
140
-
141
- var calledInOrder_1;
142
- var hasRequiredCalledInOrder;
143
-
144
- function requireCalledInOrder () {
145
- if (hasRequiredCalledInOrder) return calledInOrder_1;
146
- hasRequiredCalledInOrder = 1;
147
-
148
- var every = requireArray().every;
149
-
150
- /**
151
- * @private
152
- */
153
- function hasCallsLeft(callMap, spy) {
154
- if (callMap[spy.id] === undefined) {
155
- callMap[spy.id] = 0;
156
- }
157
-
158
- return callMap[spy.id] < spy.callCount;
159
- }
160
-
161
- /**
162
- * @private
163
- */
164
- function checkAdjacentCalls(callMap, spy, index, spies) {
165
- var calledBeforeNext = true;
166
-
167
- if (index !== spies.length - 1) {
168
- calledBeforeNext = spy.calledBefore(spies[index + 1]);
169
- }
170
-
171
- if (hasCallsLeft(callMap, spy) && calledBeforeNext) {
172
- callMap[spy.id] += 1;
173
- return true;
174
- }
175
-
176
- return false;
177
- }
178
-
179
- /**
180
- * A Sinon proxy object (fake, spy, stub)
181
- * @typedef {object} SinonProxy
182
- * @property {Function} calledBefore - A method that determines if this proxy was called before another one
183
- * @property {string} id - Some id
184
- * @property {number} callCount - Number of times this proxy has been called
185
- */
186
-
187
- /**
188
- * Returns true when the spies have been called in the order they were supplied in
189
- * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments
190
- * @returns {boolean} true when spies are called in order, false otherwise
191
- */
192
- function calledInOrder(spies) {
193
- var callMap = {};
194
- // eslint-disable-next-line no-underscore-dangle
195
- var _spies = arguments.length > 1 ? arguments : spies;
196
-
197
- return every(_spies, checkAdjacentCalls.bind(null, callMap));
198
- }
199
-
200
- calledInOrder_1 = calledInOrder;
201
- return calledInOrder_1;
202
- }
203
-
204
- var className_1;
205
- var hasRequiredClassName;
206
-
207
- function requireClassName () {
208
- if (hasRequiredClassName) return className_1;
209
- hasRequiredClassName = 1;
210
-
211
- /**
212
- * Returns a display name for a value from a constructor
213
- * @param {object} value A value to examine
214
- * @returns {(string|null)} A string or null
215
- */
216
- function className(value) {
217
- const name = value.constructor && value.constructor.name;
218
- return name || null;
219
- }
220
-
221
- className_1 = className;
222
- return className_1;
223
- }
224
-
225
- var deprecated = {};
226
-
227
- /* eslint-disable no-console */
228
-
229
- var hasRequiredDeprecated;
230
-
231
- function requireDeprecated () {
232
- if (hasRequiredDeprecated) return deprecated;
233
- hasRequiredDeprecated = 1;
234
- (function (exports$1) {
235
-
236
- /**
237
- * Returns a function that will invoke the supplied function and print a
238
- * deprecation warning to the console each time it is called.
239
- * @param {Function} func
240
- * @param {string} msg
241
- * @returns {Function}
242
- */
243
- exports$1.wrap = function (func, msg) {
244
- var wrapped = function () {
245
- exports$1.printWarning(msg);
246
- return func.apply(this, arguments);
247
- };
248
- if (func.prototype) {
249
- wrapped.prototype = func.prototype;
250
- }
251
- return wrapped;
252
- };
253
-
254
- /**
255
- * Returns a string which can be supplied to `wrap()` to notify the user that a
256
- * particular part of the sinon API has been deprecated.
257
- * @param {string} packageName
258
- * @param {string} funcName
259
- * @returns {string}
260
- */
261
- exports$1.defaultMsg = function (packageName, funcName) {
262
- return `${packageName}.${funcName} is deprecated and will be removed from the public API in a future version of ${packageName}.`;
263
- };
264
-
265
- /**
266
- * Prints a warning on the console, when it exists
267
- * @param {string} msg
268
- * @returns {undefined}
269
- */
270
- exports$1.printWarning = function (msg) {
271
- /* istanbul ignore next */
272
- if (typeof process === "object" && process.emitWarning) {
273
- // Emit Warnings in Node
274
- process.emitWarning(msg);
275
- } else if (console.info) {
276
- console.info(msg);
277
- } else {
278
- console.log(msg);
279
- }
280
- };
281
- } (deprecated));
282
- return deprecated;
283
- }
284
-
285
- var every;
286
- var hasRequiredEvery;
287
-
288
- function requireEvery () {
289
- if (hasRequiredEvery) return every;
290
- hasRequiredEvery = 1;
291
-
292
- /**
293
- * Returns true when fn returns true for all members of obj.
294
- * This is an every implementation that works for all iterables
295
- * @param {object} obj
296
- * @param {Function} fn
297
- * @returns {boolean}
298
- */
299
- every = function every(obj, fn) {
300
- var pass = true;
301
-
302
- try {
303
- // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
304
- obj.forEach(function () {
305
- if (!fn.apply(this, arguments)) {
306
- // Throwing an error is the only way to break `forEach`
307
- throw new Error();
308
- }
309
- });
310
- } catch (e) {
311
- pass = false;
312
- }
313
-
314
- return pass;
315
- };
316
- return every;
317
- }
318
-
319
- var functionName;
320
- var hasRequiredFunctionName;
321
-
322
- function requireFunctionName () {
323
- if (hasRequiredFunctionName) return functionName;
324
- hasRequiredFunctionName = 1;
325
-
326
- /**
327
- * Returns a display name for a function
328
- * @param {Function} func
329
- * @returns {string}
330
- */
331
- functionName = function functionName(func) {
332
- if (!func) {
333
- return "";
334
- }
335
-
336
- try {
337
- return (
338
- func.displayName ||
339
- func.name ||
340
- // Use function decomposition as a last resort to get function
341
- // name. Does not rely on function decomposition to work - if it
342
- // doesn't debugging will be slightly less informative
343
- // (i.e. toString will say 'spy' rather than 'myFunc').
344
- (String(func).match(/function ([^\s(]+)/) || [])[1]
345
- );
346
- } catch (e) {
347
- // Stringify may fail and we might get an exception, as a last-last
348
- // resort fall back to empty string.
349
- return "";
350
- }
351
- };
352
- return functionName;
353
- }
354
-
355
- var orderByFirstCall_1;
356
- var hasRequiredOrderByFirstCall;
357
-
358
- function requireOrderByFirstCall () {
359
- if (hasRequiredOrderByFirstCall) return orderByFirstCall_1;
360
- hasRequiredOrderByFirstCall = 1;
361
-
362
- var sort = requireArray().sort;
363
- var slice = requireArray().slice;
364
-
365
- /**
366
- * @private
367
- */
368
- function comparator(a, b) {
369
- // uuid, won't ever be equal
370
- var aCall = a.getCall(0);
371
- var bCall = b.getCall(0);
372
- var aId = (aCall && aCall.callId) || -1;
373
- var bId = (bCall && bCall.callId) || -1;
374
-
375
- return aId < bId ? -1 : 1;
376
- }
377
-
378
- /**
379
- * A Sinon proxy object (fake, spy, stub)
380
- * @typedef {object} SinonProxy
381
- * @property {Function} getCall - A method that can return the first call
382
- */
383
-
384
- /**
385
- * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call
386
- * @param {SinonProxy[] | SinonProxy} spies
387
- * @returns {SinonProxy[]}
388
- */
389
- function orderByFirstCall(spies) {
390
- return sort(slice(spies), comparator);
391
- }
392
-
393
- orderByFirstCall_1 = orderByFirstCall;
394
- return orderByFirstCall_1;
395
- }
396
-
397
- var _function;
398
- var hasRequired_function;
399
-
400
- function require_function () {
401
- if (hasRequired_function) return _function;
402
- hasRequired_function = 1;
403
-
404
- var copyPrototype = requireCopyPrototypeMethods();
405
-
406
- _function = copyPrototype(Function.prototype);
407
- return _function;
408
- }
409
-
410
- var map;
411
- var hasRequiredMap;
412
-
413
- function requireMap () {
414
- if (hasRequiredMap) return map;
415
- hasRequiredMap = 1;
416
-
417
- var copyPrototype = requireCopyPrototypeMethods();
418
-
419
- map = copyPrototype(Map.prototype);
420
- return map;
421
- }
422
-
423
- var object;
424
- var hasRequiredObject;
425
-
426
- function requireObject () {
427
- if (hasRequiredObject) return object;
428
- hasRequiredObject = 1;
429
-
430
- var copyPrototype = requireCopyPrototypeMethods();
431
-
432
- object = copyPrototype(Object.prototype);
433
- return object;
434
- }
435
-
436
- var set;
437
- var hasRequiredSet;
438
-
439
- function requireSet () {
440
- if (hasRequiredSet) return set;
441
- hasRequiredSet = 1;
442
-
443
- var copyPrototype = requireCopyPrototypeMethods();
444
-
445
- set = copyPrototype(Set.prototype);
446
- return set;
447
- }
448
-
449
- var string;
450
- var hasRequiredString;
451
-
452
- function requireString () {
453
- if (hasRequiredString) return string;
454
- hasRequiredString = 1;
455
-
456
- var copyPrototype = requireCopyPrototypeMethods();
457
-
458
- string = copyPrototype(String.prototype);
459
- return string;
460
- }
461
-
462
- var prototypes;
463
- var hasRequiredPrototypes;
464
-
465
- function requirePrototypes () {
466
- if (hasRequiredPrototypes) return prototypes;
467
- hasRequiredPrototypes = 1;
468
-
469
- prototypes = {
470
- array: requireArray(),
471
- function: require_function(),
472
- map: requireMap(),
473
- object: requireObject(),
474
- set: requireSet(),
475
- string: requireString(),
476
- };
477
- return prototypes;
478
- }
479
-
480
- var typeDetect$1 = {exports: {}};
481
-
482
- var typeDetect = typeDetect$1.exports;
483
-
484
- var hasRequiredTypeDetect;
485
-
486
- function requireTypeDetect () {
487
- if (hasRequiredTypeDetect) return typeDetect$1.exports;
488
- hasRequiredTypeDetect = 1;
489
- (function (module, exports$1) {
490
- (function (global, factory) {
491
- module.exports = factory() ;
492
- }(typeDetect, (function () {
493
- /* !
494
- * type-detect
495
- * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
496
- * MIT Licensed
497
- */
498
- var promiseExists = typeof Promise === 'function';
499
-
500
- /* eslint-disable no-undef */
501
- var globalObject = typeof self === 'object' ? self : commonjsGlobal; // eslint-disable-line id-blacklist
502
-
503
- var symbolExists = typeof Symbol !== 'undefined';
504
- var mapExists = typeof Map !== 'undefined';
505
- var setExists = typeof Set !== 'undefined';
506
- var weakMapExists = typeof WeakMap !== 'undefined';
507
- var weakSetExists = typeof WeakSet !== 'undefined';
508
- var dataViewExists = typeof DataView !== 'undefined';
509
- var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined';
510
- var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined';
511
- var setEntriesExists = setExists && typeof Set.prototype.entries === 'function';
512
- var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function';
513
- var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries());
514
- var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries());
515
- var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function';
516
- var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]());
517
- var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function';
518
- var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]());
519
- var toStringLeftSliceLength = 8;
520
- var toStringRightSliceLength = -1;
521
- /**
522
- * ### typeOf (obj)
523
- *
524
- * Uses `Object.prototype.toString` to determine the type of an object,
525
- * normalising behaviour across engine versions & well optimised.
526
- *
527
- * @param {Mixed} object
528
- * @return {String} object type
529
- * @api public
530
- */
531
- function typeDetect(obj) {
532
- /* ! Speed optimisation
533
- * Pre:
534
- * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled)
535
- * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled)
536
- * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled)
537
- * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled)
538
- * function x 2,556,769 ops/sec ±1.73% (77 runs sampled)
539
- * Post:
540
- * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled)
541
- * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled)
542
- * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled)
543
- * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled)
544
- * function x 31,296,870 ops/sec ±0.96% (83 runs sampled)
545
- */
546
- var typeofObj = typeof obj;
547
- if (typeofObj !== 'object') {
548
- return typeofObj;
549
- }
550
-
551
- /* ! Speed optimisation
552
- * Pre:
553
- * null x 28,645,765 ops/sec ±1.17% (82 runs sampled)
554
- * Post:
555
- * null x 36,428,962 ops/sec ±1.37% (84 runs sampled)
556
- */
557
- if (obj === null) {
558
- return 'null';
559
- }
560
-
561
- /* ! Spec Conformance
562
- * Test: `Object.prototype.toString.call(window)``
563
- * - Node === "[object global]"
564
- * - Chrome === "[object global]"
565
- * - Firefox === "[object Window]"
566
- * - PhantomJS === "[object Window]"
567
- * - Safari === "[object Window]"
568
- * - IE 11 === "[object Window]"
569
- * - IE Edge === "[object Window]"
570
- * Test: `Object.prototype.toString.call(this)``
571
- * - Chrome Worker === "[object global]"
572
- * - Firefox Worker === "[object DedicatedWorkerGlobalScope]"
573
- * - Safari Worker === "[object DedicatedWorkerGlobalScope]"
574
- * - IE 11 Worker === "[object WorkerGlobalScope]"
575
- * - IE Edge Worker === "[object WorkerGlobalScope]"
576
- */
577
- if (obj === globalObject) {
578
- return 'global';
579
- }
580
-
581
- /* ! Speed optimisation
582
- * Pre:
583
- * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled)
584
- * Post:
585
- * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled)
586
- */
587
- if (
588
- Array.isArray(obj) &&
589
- (symbolToStringTagExists === false || !(Symbol.toStringTag in obj))
590
- ) {
591
- return 'Array';
592
- }
593
-
594
- // Not caching existence of `window` and related properties due to potential
595
- // for `window` to be unset before tests in quasi-browser environments.
596
- if (typeof window === 'object' && window !== null) {
597
- /* ! Spec Conformance
598
- * (https://html.spec.whatwg.org/multipage/browsers.html#location)
599
- * WhatWG HTML$7.7.3 - The `Location` interface
600
- * Test: `Object.prototype.toString.call(window.location)``
601
- * - IE <=11 === "[object Object]"
602
- * - IE Edge <=13 === "[object Object]"
603
- */
604
- if (typeof window.location === 'object' && obj === window.location) {
605
- return 'Location';
606
- }
607
-
608
- /* ! Spec Conformance
609
- * (https://html.spec.whatwg.org/#document)
610
- * WhatWG HTML$3.1.1 - The `Document` object
611
- * Note: Most browsers currently adher to the W3C DOM Level 2 spec
612
- * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268)
613
- * which suggests that browsers should use HTMLTableCellElement for
614
- * both TD and TH elements. WhatWG separates these.
615
- * WhatWG HTML states:
616
- * > For historical reasons, Window objects must also have a
617
- * > writable, configurable, non-enumerable property named
618
- * > HTMLDocument whose value is the Document interface object.
619
- * Test: `Object.prototype.toString.call(document)``
620
- * - Chrome === "[object HTMLDocument]"
621
- * - Firefox === "[object HTMLDocument]"
622
- * - Safari === "[object HTMLDocument]"
623
- * - IE <=10 === "[object Document]"
624
- * - IE 11 === "[object HTMLDocument]"
625
- * - IE Edge <=13 === "[object HTMLDocument]"
626
- */
627
- if (typeof window.document === 'object' && obj === window.document) {
628
- return 'Document';
629
- }
630
-
631
- if (typeof window.navigator === 'object') {
632
- /* ! Spec Conformance
633
- * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray)
634
- * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray
635
- * Test: `Object.prototype.toString.call(navigator.mimeTypes)``
636
- * - IE <=10 === "[object MSMimeTypesCollection]"
637
- */
638
- if (typeof window.navigator.mimeTypes === 'object' &&
639
- obj === window.navigator.mimeTypes) {
640
- return 'MimeTypeArray';
641
- }
642
-
643
- /* ! Spec Conformance
644
- * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
645
- * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray
646
- * Test: `Object.prototype.toString.call(navigator.plugins)``
647
- * - IE <=10 === "[object MSPluginsCollection]"
648
- */
649
- if (typeof window.navigator.plugins === 'object' &&
650
- obj === window.navigator.plugins) {
651
- return 'PluginArray';
652
- }
653
- }
654
-
655
- if ((typeof window.HTMLElement === 'function' ||
656
- typeof window.HTMLElement === 'object') &&
657
- obj instanceof window.HTMLElement) {
658
- /* ! Spec Conformance
659
- * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
660
- * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement`
661
- * Test: `Object.prototype.toString.call(document.createElement('blockquote'))``
662
- * - IE <=10 === "[object HTMLBlockElement]"
663
- */
664
- if (obj.tagName === 'BLOCKQUOTE') {
665
- return 'HTMLQuoteElement';
666
- }
667
-
668
- /* ! Spec Conformance
669
- * (https://html.spec.whatwg.org/#htmltabledatacellelement)
670
- * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement`
671
- * Note: Most browsers currently adher to the W3C DOM Level 2 spec
672
- * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
673
- * which suggests that browsers should use HTMLTableCellElement for
674
- * both TD and TH elements. WhatWG separates these.
675
- * Test: Object.prototype.toString.call(document.createElement('td'))
676
- * - Chrome === "[object HTMLTableCellElement]"
677
- * - Firefox === "[object HTMLTableCellElement]"
678
- * - Safari === "[object HTMLTableCellElement]"
679
- */
680
- if (obj.tagName === 'TD') {
681
- return 'HTMLTableDataCellElement';
682
- }
683
-
684
- /* ! Spec Conformance
685
- * (https://html.spec.whatwg.org/#htmltableheadercellelement)
686
- * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement`
687
- * Note: Most browsers currently adher to the W3C DOM Level 2 spec
688
- * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
689
- * which suggests that browsers should use HTMLTableCellElement for
690
- * both TD and TH elements. WhatWG separates these.
691
- * Test: Object.prototype.toString.call(document.createElement('th'))
692
- * - Chrome === "[object HTMLTableCellElement]"
693
- * - Firefox === "[object HTMLTableCellElement]"
694
- * - Safari === "[object HTMLTableCellElement]"
695
- */
696
- if (obj.tagName === 'TH') {
697
- return 'HTMLTableHeaderCellElement';
698
- }
699
- }
700
- }
701
-
702
- /* ! Speed optimisation
703
- * Pre:
704
- * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled)
705
- * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled)
706
- * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled)
707
- * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled)
708
- * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled)
709
- * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled)
710
- * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled)
711
- * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled)
712
- * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled)
713
- * Post:
714
- * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled)
715
- * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled)
716
- * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled)
717
- * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled)
718
- * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled)
719
- * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled)
720
- * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled)
721
- * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled)
722
- * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled)
723
- */
724
- var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]);
725
- if (typeof stringTag === 'string') {
726
- return stringTag;
727
- }
728
-
729
- var objPrototype = Object.getPrototypeOf(obj);
730
- /* ! Speed optimisation
731
- * Pre:
732
- * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled)
733
- * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled)
734
- * Post:
735
- * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled)
736
- * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled)
737
- */
738
- if (objPrototype === RegExp.prototype) {
739
- return 'RegExp';
740
- }
741
-
742
- /* ! Speed optimisation
743
- * Pre:
744
- * date x 2,130,074 ops/sec ±4.42% (68 runs sampled)
745
- * Post:
746
- * date x 3,953,779 ops/sec ±1.35% (77 runs sampled)
747
- */
748
- if (objPrototype === Date.prototype) {
749
- return 'Date';
750
- }
751
-
752
- /* ! Spec Conformance
753
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag)
754
- * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise":
755
- * Test: `Object.prototype.toString.call(Promise.resolve())``
756
- * - Chrome <=47 === "[object Object]"
757
- * - Edge <=20 === "[object Object]"
758
- * - Firefox 29-Latest === "[object Promise]"
759
- * - Safari 7.1-Latest === "[object Promise]"
760
- */
761
- if (promiseExists && objPrototype === Promise.prototype) {
762
- return 'Promise';
763
- }
764
-
765
- /* ! Speed optimisation
766
- * Pre:
767
- * set x 2,222,186 ops/sec ±1.31% (82 runs sampled)
768
- * Post:
769
- * set x 4,545,879 ops/sec ±1.13% (83 runs sampled)
770
- */
771
- if (setExists && objPrototype === Set.prototype) {
772
- return 'Set';
773
- }
774
-
775
- /* ! Speed optimisation
776
- * Pre:
777
- * map x 2,396,842 ops/sec ±1.59% (81 runs sampled)
778
- * Post:
779
- * map x 4,183,945 ops/sec ±6.59% (82 runs sampled)
780
- */
781
- if (mapExists && objPrototype === Map.prototype) {
782
- return 'Map';
783
- }
784
-
785
- /* ! Speed optimisation
786
- * Pre:
787
- * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled)
788
- * Post:
789
- * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled)
790
- */
791
- if (weakSetExists && objPrototype === WeakSet.prototype) {
792
- return 'WeakSet';
793
- }
794
-
795
- /* ! Speed optimisation
796
- * Pre:
797
- * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled)
798
- * Post:
799
- * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled)
800
- */
801
- if (weakMapExists && objPrototype === WeakMap.prototype) {
802
- return 'WeakMap';
803
- }
804
-
805
- /* ! Spec Conformance
806
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag)
807
- * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView":
808
- * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))``
809
- * - Edge <=13 === "[object Object]"
810
- */
811
- if (dataViewExists && objPrototype === DataView.prototype) {
812
- return 'DataView';
813
- }
814
-
815
- /* ! Spec Conformance
816
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag)
817
- * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator":
818
- * Test: `Object.prototype.toString.call(new Map().entries())``
819
- * - Edge <=13 === "[object Object]"
820
- */
821
- if (mapExists && objPrototype === mapIteratorPrototype) {
822
- return 'Map Iterator';
823
- }
824
-
825
- /* ! Spec Conformance
826
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag)
827
- * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator":
828
- * Test: `Object.prototype.toString.call(new Set().entries())``
829
- * - Edge <=13 === "[object Object]"
830
- */
831
- if (setExists && objPrototype === setIteratorPrototype) {
832
- return 'Set Iterator';
833
- }
834
-
835
- /* ! Spec Conformance
836
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag)
837
- * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator":
838
- * Test: `Object.prototype.toString.call([][Symbol.iterator]())``
839
- * - Edge <=13 === "[object Object]"
840
- */
841
- if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) {
842
- return 'Array Iterator';
843
- }
844
-
845
- /* ! Spec Conformance
846
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag)
847
- * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator":
848
- * Test: `Object.prototype.toString.call(''[Symbol.iterator]())``
849
- * - Edge <=13 === "[object Object]"
850
- */
851
- if (stringIteratorExists && objPrototype === stringIteratorPrototype) {
852
- return 'String Iterator';
853
- }
854
-
855
- /* ! Speed optimisation
856
- * Pre:
857
- * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled)
858
- * Post:
859
- * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled)
860
- */
861
- if (objPrototype === null) {
862
- return 'Object';
863
- }
864
-
865
- return Object
866
- .prototype
867
- .toString
868
- .call(obj)
869
- .slice(toStringLeftSliceLength, toStringRightSliceLength);
870
- }
871
-
872
- return typeDetect;
873
-
874
- })));
875
- } (typeDetect$1));
876
- return typeDetect$1.exports;
877
- }
878
-
879
- var typeOf;
880
- var hasRequiredTypeOf;
881
-
882
- function requireTypeOf () {
883
- if (hasRequiredTypeOf) return typeOf;
884
- hasRequiredTypeOf = 1;
885
-
886
- var type = requireTypeDetect();
887
-
888
- /**
889
- * Returns the lower-case result of running type from type-detect on the value
890
- * @param {*} value
891
- * @returns {string}
892
- */
893
- typeOf = function typeOf(value) {
894
- return type(value).toLowerCase();
895
- };
896
- return typeOf;
897
- }
898
-
899
- var valueToString_1;
900
- var hasRequiredValueToString;
901
-
902
- function requireValueToString () {
903
- if (hasRequiredValueToString) return valueToString_1;
904
- hasRequiredValueToString = 1;
905
-
906
- /**
907
- * Returns a string representation of the value
908
- * @param {*} value
909
- * @returns {string}
910
- */
911
- function valueToString(value) {
912
- if (value && value.toString) {
913
- // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
914
- return value.toString();
915
- }
916
- return String(value);
917
- }
918
-
919
- valueToString_1 = valueToString;
920
- return valueToString_1;
921
- }
922
-
923
- var lib;
924
- var hasRequiredLib;
925
-
926
- function requireLib () {
927
- if (hasRequiredLib) return lib;
928
- hasRequiredLib = 1;
929
-
930
- lib = {
931
- global: requireGlobal(),
932
- calledInOrder: requireCalledInOrder(),
933
- className: requireClassName(),
934
- deprecated: requireDeprecated(),
935
- every: requireEvery(),
936
- functionName: requireFunctionName(),
937
- orderByFirstCall: requireOrderByFirstCall(),
938
- prototypes: requirePrototypes(),
939
- typeOf: requireTypeOf(),
940
- valueToString: requireValueToString(),
941
- };
942
- return lib;
943
- }
944
-
945
- var hasRequiredFakeTimersSrc;
946
-
947
- function requireFakeTimersSrc () {
948
- if (hasRequiredFakeTimersSrc) return fakeTimersSrc;
949
- hasRequiredFakeTimersSrc = 1;
950
-
951
- const globalObject = requireLib().global;
952
- let timersModule, timersPromisesModule;
953
- if (typeof __vitest_required__ !== 'undefined') {
954
- try {
955
- timersModule = __vitest_required__.timers;
956
- } catch (e) {
957
- // ignored
958
- }
959
- try {
960
- timersPromisesModule = __vitest_required__.timersPromises;
961
- } catch (e) {
962
- // ignored
963
- }
964
- }
965
-
966
- /**
967
- * @typedef {"nextAsync" | "manual" | "interval"} TickMode
968
- */
969
-
970
- /**
971
- * @typedef {object} NextAsyncTickMode
972
- * @property {"nextAsync"} mode
973
- */
974
-
975
- /**
976
- * @typedef {object} ManualTickMode
977
- * @property {"manual"} mode
978
- */
979
-
980
- /**
981
- * @typedef {object} IntervalTickMode
982
- * @property {"interval"} mode
983
- * @property {number} [delta]
984
- */
985
-
986
- /**
987
- * @typedef {IntervalTickMode | NextAsyncTickMode | ManualTickMode} TimerTickMode
988
- */
989
-
990
- /**
991
- * @typedef {object} IdleDeadline
992
- * @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout
993
- * @property {function():number} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period
994
- */
995
-
996
- /**
997
- * Queues a function to be called during a browser's idle periods
998
- * @callback RequestIdleCallback
999
- * @param {function(IdleDeadline)} callback
1000
- * @param {{timeout: number}} options - an options object
1001
- * @returns {number} the id
1002
- */
1003
-
1004
- /**
1005
- * @callback NextTick
1006
- * @param {VoidVarArgsFunc} callback - the callback to run
1007
- * @param {...*} args - optional arguments to call the callback with
1008
- * @returns {void}
1009
- */
1010
-
1011
- /**
1012
- * @callback SetImmediate
1013
- * @param {VoidVarArgsFunc} callback - the callback to run
1014
- * @param {...*} args - optional arguments to call the callback with
1015
- * @returns {NodeImmediate}
1016
- */
1017
-
1018
- /**
1019
- * @callback VoidVarArgsFunc
1020
- * @param {...*} callback - the callback to run
1021
- * @returns {void}
1022
- */
1023
-
1024
- /**
1025
- * @typedef RequestAnimationFrame
1026
- * @property {function(number):void} requestAnimationFrame
1027
- * @returns {number} - the id
1028
- */
1029
-
1030
- /**
1031
- * @typedef Performance
1032
- * @property {function(): number} now
1033
- */
1034
-
1035
- /* eslint-disable jsdoc/require-property-description */
1036
- /**
1037
- * @typedef {object} Clock
1038
- * @property {number} now - the current time
1039
- * @property {Date} Date - the Date constructor
1040
- * @property {number} loopLimit - the maximum number of timers before assuming an infinite loop
1041
- * @property {RequestIdleCallback} requestIdleCallback
1042
- * @property {function(number):void} cancelIdleCallback
1043
- * @property {setTimeout} setTimeout
1044
- * @property {clearTimeout} clearTimeout
1045
- * @property {NextTick} nextTick
1046
- * @property {queueMicrotask} queueMicrotask
1047
- * @property {setInterval} setInterval
1048
- * @property {clearInterval} clearInterval
1049
- * @property {SetImmediate} setImmediate
1050
- * @property {function(NodeImmediate):void} clearImmediate
1051
- * @property {function():number} countTimers
1052
- * @property {RequestAnimationFrame} requestAnimationFrame
1053
- * @property {function(number):void} cancelAnimationFrame
1054
- * @property {function():void} runMicrotasks
1055
- * @property {function(string | number): number} tick
1056
- * @property {function(string | number): Promise<number>} tickAsync
1057
- * @property {function(): number} next
1058
- * @property {function(): Promise<number>} nextAsync
1059
- * @property {function(): number} runAll
1060
- * @property {function(): number} runToFrame
1061
- * @property {function(): Promise<number>} runAllAsync
1062
- * @property {function(): number} runToLast
1063
- * @property {function(): Promise<number>} runToLastAsync
1064
- * @property {function(): void} reset
1065
- * @property {function(number | Date): void} setSystemTime
1066
- * @property {function(number): void} jump
1067
- * @property {Performance} performance
1068
- * @property {function(number[]): number[]} hrtime - process.hrtime (legacy)
1069
- * @property {function(): void} uninstall Uninstall the clock.
1070
- * @property {Function[]} methods - the methods that are faked
1071
- * @property {boolean} [shouldClearNativeTimers] inherited from config
1072
- * @property {{methodName:string, original:any}[] | undefined} timersModuleMethods
1073
- * @property {{methodName:string, original:any}[] | undefined} timersPromisesModuleMethods
1074
- * @property {Map<function(): void, AbortSignal>} abortListenerMap
1075
- * @property {function(TimerTickMode): void} setTickMode
1076
- */
1077
- /* eslint-enable jsdoc/require-property-description */
1078
-
1079
- /**
1080
- * Configuration object for the `install` method.
1081
- * @typedef {object} Config
1082
- * @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch)
1083
- * @property {string[]} [toFake] names of the methods that should be faked.
1084
- * @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll()
1085
- * @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false)
1086
- * @property {number} [advanceTimeDelta] increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
1087
- * @property {boolean} [shouldClearNativeTimers] forwards clear timer calls to native functions if they are not fakes (default: false)
1088
- * @property {boolean} [ignoreMissingTimers] default is false, meaning asking to fake timers that are not present will throw an error
1089
- */
1090
-
1091
- /* eslint-disable jsdoc/require-property-description */
1092
- /**
1093
- * The internal structure to describe a scheduled fake timer
1094
- * @typedef {object} Timer
1095
- * @property {Function} func
1096
- * @property {*[]} args
1097
- * @property {number} delay
1098
- * @property {number} callAt
1099
- * @property {number} createdAt
1100
- * @property {boolean} immediate
1101
- * @property {number} id
1102
- * @property {Error} [error]
1103
- */
1104
-
1105
- /**
1106
- * A Node timer
1107
- * @typedef {object} NodeImmediate
1108
- * @property {function(): boolean} hasRef
1109
- * @property {function(): NodeImmediate} ref
1110
- * @property {function(): NodeImmediate} unref
1111
- */
1112
- /* eslint-enable jsdoc/require-property-description */
1113
-
1114
- /* eslint-disable complexity */
1115
-
1116
- /**
1117
- * Mocks available features in the specified global namespace.
1118
- * @param {*} _global Namespace to mock (e.g. `window`)
1119
- * @returns {FakeTimers}
1120
- */
1121
- function withGlobal(_global) {
1122
- const maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
1123
- const idCounterStart = 1e12; // arbitrarily large number to avoid collisions with native timer IDs
1124
- const NOOP = function () {
1125
- return undefined;
1126
- };
1127
- const NOOP_ARRAY = function () {
1128
- return [];
1129
- };
1130
- const isPresent = {};
1131
- let timeoutResult,
1132
- addTimerReturnsObject = false;
1133
-
1134
- if (_global.setTimeout) {
1135
- isPresent.setTimeout = true;
1136
- timeoutResult = _global.setTimeout(NOOP, 0);
1137
- addTimerReturnsObject = typeof timeoutResult === "object";
1138
- }
1139
- isPresent.clearTimeout = Boolean(_global.clearTimeout);
1140
- isPresent.setInterval = Boolean(_global.setInterval);
1141
- isPresent.clearInterval = Boolean(_global.clearInterval);
1142
- isPresent.hrtime =
1143
- _global.process && typeof _global.process.hrtime === "function";
1144
- isPresent.hrtimeBigint =
1145
- isPresent.hrtime && typeof _global.process.hrtime.bigint === "function";
1146
- isPresent.nextTick =
1147
- _global.process && typeof _global.process.nextTick === "function";
1148
- const utilPromisify = _global.process && _global.__vitest_required__ && _global.__vitest_required__.util.promisify;
1149
- isPresent.performance =
1150
- _global.performance && typeof _global.performance.now === "function";
1151
- const hasPerformancePrototype =
1152
- _global.Performance &&
1153
- (typeof _global.Performance).match(/^(function|object)$/);
1154
- const hasPerformanceConstructorPrototype =
1155
- _global.performance &&
1156
- _global.performance.constructor &&
1157
- _global.performance.constructor.prototype;
1158
- isPresent.queueMicrotask = _global.hasOwnProperty("queueMicrotask");
1159
- isPresent.requestAnimationFrame =
1160
- _global.requestAnimationFrame &&
1161
- typeof _global.requestAnimationFrame === "function";
1162
- isPresent.cancelAnimationFrame =
1163
- _global.cancelAnimationFrame &&
1164
- typeof _global.cancelAnimationFrame === "function";
1165
- isPresent.requestIdleCallback =
1166
- _global.requestIdleCallback &&
1167
- typeof _global.requestIdleCallback === "function";
1168
- isPresent.cancelIdleCallbackPresent =
1169
- _global.cancelIdleCallback &&
1170
- typeof _global.cancelIdleCallback === "function";
1171
- isPresent.setImmediate =
1172
- _global.setImmediate && typeof _global.setImmediate === "function";
1173
- isPresent.clearImmediate =
1174
- _global.clearImmediate && typeof _global.clearImmediate === "function";
1175
- isPresent.Intl = _global.Intl && typeof _global.Intl === "object";
1176
-
1177
- if (_global.clearTimeout) {
1178
- _global.clearTimeout(timeoutResult);
1179
- }
1180
-
1181
- const NativeDate = _global.Date;
1182
- const NativeIntl = isPresent.Intl
1183
- ? Object.defineProperties(
1184
- Object.create(null),
1185
- Object.getOwnPropertyDescriptors(_global.Intl),
1186
- )
1187
- : undefined;
1188
- let uniqueTimerId = idCounterStart;
1189
-
1190
- if (NativeDate === undefined) {
1191
- throw new Error(
1192
- "The global scope doesn't have a `Date` object" +
1193
- " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)",
1194
- );
1195
- }
1196
- isPresent.Date = true;
1197
-
1198
- /**
1199
- * The PerformanceEntry object encapsulates a single performance metric
1200
- * that is part of the browser's performance timeline.
1201
- *
1202
- * This is an object returned by the `mark` and `measure` methods on the Performance prototype
1203
- */
1204
- class FakePerformanceEntry {
1205
- constructor(name, entryType, startTime, duration) {
1206
- this.name = name;
1207
- this.entryType = entryType;
1208
- this.startTime = startTime;
1209
- this.duration = duration;
1210
- }
1211
-
1212
- toJSON() {
1213
- return JSON.stringify({ ...this });
1214
- }
1215
- }
1216
-
1217
- /**
1218
- * @param {number} num
1219
- * @returns {boolean}
1220
- */
1221
- function isNumberFinite(num) {
1222
- if (Number.isFinite) {
1223
- return Number.isFinite(num);
1224
- }
1225
-
1226
- return isFinite(num);
1227
- }
1228
-
1229
- let isNearInfiniteLimit = false;
1230
-
1231
- /**
1232
- * @param {Clock} clock
1233
- * @param {number} i
1234
- */
1235
- function checkIsNearInfiniteLimit(clock, i) {
1236
- if (clock.loopLimit && i === clock.loopLimit - 1) {
1237
- isNearInfiniteLimit = true;
1238
- }
1239
- }
1240
-
1241
- /**
1242
- *
1243
- */
1244
- function resetIsNearInfiniteLimit() {
1245
- isNearInfiniteLimit = false;
1246
- }
1247
-
1248
- /**
1249
- * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
1250
- * number of milliseconds. This is used to support human-readable strings passed
1251
- * to clock.tick()
1252
- * @param {string} str
1253
- * @returns {number}
1254
- */
1255
- function parseTime(str) {
1256
- if (!str) {
1257
- return 0;
1258
- }
1259
-
1260
- const strings = str.split(":");
1261
- const l = strings.length;
1262
- let i = l;
1263
- let ms = 0;
1264
- let parsed;
1265
-
1266
- if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
1267
- throw new Error(
1268
- "tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits",
1269
- );
1270
- }
1271
-
1272
- while (i--) {
1273
- parsed = parseInt(strings[i], 10);
1274
-
1275
- if (parsed >= 60) {
1276
- throw new Error(`Invalid time ${str}`);
1277
- }
1278
-
1279
- ms += parsed * Math.pow(60, l - i - 1);
1280
- }
1281
-
1282
- return ms * 1000;
1283
- }
1284
-
1285
- /**
1286
- * Get the decimal part of the millisecond value as nanoseconds
1287
- * @param {number} msFloat the number of milliseconds
1288
- * @returns {number} an integer number of nanoseconds in the range [0,1e6)
1289
- *
1290
- * Example: nanoRemainer(123.456789) -> 456789
1291
- */
1292
- function nanoRemainder(msFloat) {
1293
- const modulo = 1e6;
1294
- const remainder = (msFloat * 1e6) % modulo;
1295
- const positiveRemainder =
1296
- remainder < 0 ? remainder + modulo : remainder;
1297
-
1298
- return Math.floor(positiveRemainder);
1299
- }
1300
-
1301
- /**
1302
- * Used to grok the `now` parameter to createClock.
1303
- * @param {Date|number} epoch the system time
1304
- * @returns {number}
1305
- */
1306
- function getEpoch(epoch) {
1307
- if (!epoch) {
1308
- return 0;
1309
- }
1310
- if (typeof epoch.getTime === "function") {
1311
- return epoch.getTime();
1312
- }
1313
- if (typeof epoch === "number") {
1314
- return epoch;
1315
- }
1316
- throw new TypeError("now should be milliseconds since UNIX epoch");
1317
- }
1318
-
1319
- /**
1320
- * @param {number} from
1321
- * @param {number} to
1322
- * @param {Timer} timer
1323
- * @returns {boolean}
1324
- */
1325
- function inRange(from, to, timer) {
1326
- return timer && timer.callAt >= from && timer.callAt <= to;
1327
- }
1328
-
1329
- /**
1330
- * @param {Clock} clock
1331
- * @param {Timer} job
1332
- */
1333
- function getInfiniteLoopError(clock, job) {
1334
- const infiniteLoopError = new Error(
1335
- `Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!`,
1336
- );
1337
-
1338
- if (!job.error) {
1339
- return infiniteLoopError;
1340
- }
1341
-
1342
- // pattern never matched in Node
1343
- const computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/;
1344
- let clockMethodPattern = new RegExp(
1345
- String(Object.keys(clock).join("|")),
1346
- );
1347
-
1348
- if (addTimerReturnsObject) {
1349
- // node.js environment
1350
- clockMethodPattern = new RegExp(
1351
- `\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+`,
1352
- );
1353
- }
1354
-
1355
- let matchedLineIndex = -1;
1356
- job.error.stack.split("\n").some(function (line, i) {
1357
- // If we've matched a computed target line (e.g. setTimeout) then we
1358
- // don't need to look any further. Return true to stop iterating.
1359
- const matchedComputedTarget = line.match(computedTargetPattern);
1360
- /* istanbul ignore if */
1361
- if (matchedComputedTarget) {
1362
- matchedLineIndex = i;
1363
- return true;
1364
- }
1365
-
1366
- // If we've matched a clock method line, then there may still be
1367
- // others further down the trace. Return false to keep iterating.
1368
- const matchedClockMethod = line.match(clockMethodPattern);
1369
- if (matchedClockMethod) {
1370
- matchedLineIndex = i;
1371
- return false;
1372
- }
1373
-
1374
- // If we haven't matched anything on this line, but we matched
1375
- // previously and set the matched line index, then we can stop.
1376
- // If we haven't matched previously, then we should keep iterating.
1377
- return matchedLineIndex >= 0;
1378
- });
1379
-
1380
- const stack = `${infiniteLoopError}\n${job.type || "Microtask"} - ${
1381
- job.func.name || "anonymous"
1382
- }\n${job.error.stack
1383
- .split("\n")
1384
- .slice(matchedLineIndex + 1)
1385
- .join("\n")}`;
1386
-
1387
- try {
1388
- Object.defineProperty(infiniteLoopError, "stack", {
1389
- value: stack,
1390
- });
1391
- } catch (e) {
1392
- // noop
1393
- }
1394
-
1395
- return infiniteLoopError;
1396
- }
1397
-
1398
- //eslint-disable-next-line jsdoc/require-jsdoc
1399
- function createDate() {
1400
- class ClockDate extends NativeDate {
1401
- /**
1402
- * @param {number} year
1403
- * @param {number} month
1404
- * @param {number} date
1405
- * @param {number} hour
1406
- * @param {number} minute
1407
- * @param {number} second
1408
- * @param {number} ms
1409
- * @returns void
1410
- */
1411
- // eslint-disable-next-line no-unused-vars
1412
- constructor(year, month, date, hour, minute, second, ms) {
1413
- // Defensive and verbose to avoid potential harm in passing
1414
- // explicit undefined when user does not pass argument
1415
- if (arguments.length === 0) {
1416
- super(ClockDate.clock.now);
1417
- } else {
1418
- super(...arguments);
1419
- }
1420
-
1421
- // ensures identity checks using the constructor prop still works
1422
- // this should have no other functional effect
1423
- Object.defineProperty(this, "constructor", {
1424
- value: NativeDate,
1425
- enumerable: false,
1426
- });
1427
- }
1428
-
1429
- static [Symbol.hasInstance](instance) {
1430
- return instance instanceof NativeDate;
1431
- }
1432
- }
1433
-
1434
- ClockDate.isFake = true;
1435
-
1436
- if (NativeDate.now) {
1437
- ClockDate.now = function now() {
1438
- return ClockDate.clock.now;
1439
- };
1440
- }
1441
-
1442
- if (NativeDate.toSource) {
1443
- ClockDate.toSource = function toSource() {
1444
- return NativeDate.toSource();
1445
- };
1446
- }
1447
-
1448
- ClockDate.toString = function toString() {
1449
- return NativeDate.toString();
1450
- };
1451
-
1452
- // noinspection UnnecessaryLocalVariableJS
1453
- /**
1454
- * A normal Class constructor cannot be called without `new`, but Date can, so we need
1455
- * to wrap it in a Proxy in order to ensure this functionality of Date is kept intact
1456
- * @type {ClockDate}
1457
- */
1458
- const ClockDateProxy = new Proxy(ClockDate, {
1459
- // handler for [[Call]] invocations (i.e. not using `new`)
1460
- apply() {
1461
- // the Date constructor called as a function, ref Ecma-262 Edition 5.1, section 15.9.2.
1462
- // This remains so in the 10th edition of 2019 as well.
1463
- if (this instanceof ClockDate) {
1464
- throw new TypeError(
1465
- "A Proxy should only capture `new` calls with the `construct` handler. This is not supposed to be possible, so check the logic.",
1466
- );
1467
- }
1468
-
1469
- return new NativeDate(ClockDate.clock.now).toString();
1470
- },
1471
- });
1472
-
1473
- return ClockDateProxy;
1474
- }
1475
-
1476
- /**
1477
- * Mirror Intl by default on our fake implementation
1478
- *
1479
- * Most of the properties are the original native ones,
1480
- * but we need to take control of those that have a
1481
- * dependency on the current clock.
1482
- * @returns {object} the partly fake Intl implementation
1483
- */
1484
- function createIntl() {
1485
- const ClockIntl = {};
1486
- /*
1487
- * All properties of Intl are non-enumerable, so we need
1488
- * to do a bit of work to get them out.
1489
- */
1490
- Object.getOwnPropertyNames(NativeIntl).forEach(
1491
- (property) => (ClockIntl[property] = NativeIntl[property]),
1492
- );
1493
-
1494
- ClockIntl.DateTimeFormat = function (...args) {
1495
- const realFormatter = new NativeIntl.DateTimeFormat(...args);
1496
- const formatter = {};
1497
-
1498
- ["formatRange", "formatRangeToParts", "resolvedOptions"].forEach(
1499
- (method) => {
1500
- formatter[method] =
1501
- realFormatter[method].bind(realFormatter);
1502
- },
1503
- );
1504
-
1505
- ["format", "formatToParts"].forEach((method) => {
1506
- formatter[method] = function (date) {
1507
- return realFormatter[method](date || ClockIntl.clock.now);
1508
- };
1509
- });
1510
-
1511
- return formatter;
1512
- };
1513
-
1514
- ClockIntl.DateTimeFormat.prototype = Object.create(
1515
- NativeIntl.DateTimeFormat.prototype,
1516
- );
1517
-
1518
- ClockIntl.DateTimeFormat.supportedLocalesOf =
1519
- NativeIntl.DateTimeFormat.supportedLocalesOf;
1520
-
1521
- return ClockIntl;
1522
- }
1523
-
1524
- //eslint-disable-next-line jsdoc/require-jsdoc
1525
- function enqueueJob(clock, job) {
1526
- // enqueues a microtick-deferred task - ecma262/#sec-enqueuejob
1527
- if (!clock.jobs) {
1528
- clock.jobs = [];
1529
- }
1530
- clock.jobs.push(job);
1531
- }
1532
-
1533
- //eslint-disable-next-line jsdoc/require-jsdoc
1534
- function runJobs(clock) {
1535
- // runs all microtick-deferred tasks - ecma262/#sec-runjobs
1536
- if (!clock.jobs) {
1537
- return;
1538
- }
1539
- for (let i = 0; i < clock.jobs.length; i++) {
1540
- const job = clock.jobs[i];
1541
- job.func.apply(null, job.args);
1542
-
1543
- checkIsNearInfiniteLimit(clock, i);
1544
- if (clock.loopLimit && i > clock.loopLimit) {
1545
- throw getInfiniteLoopError(clock, job);
1546
- }
1547
- }
1548
- resetIsNearInfiniteLimit();
1549
- clock.jobs = [];
1550
- }
1551
-
1552
- /**
1553
- * @param {Clock} clock
1554
- * @param {Timer} timer
1555
- * @returns {number} id of the created timer
1556
- */
1557
- function addTimer(clock, timer) {
1558
- if (timer.func === undefined) {
1559
- throw new Error("Callback must be provided to timer calls");
1560
- }
1561
-
1562
- if (addTimerReturnsObject) {
1563
- // Node.js environment
1564
- if (typeof timer.func !== "function") {
1565
- throw new TypeError(
1566
- `[ERR_INVALID_CALLBACK]: Callback must be a function. Received ${
1567
- timer.func
1568
- } of type ${typeof timer.func}`,
1569
- );
1570
- }
1571
- }
1572
-
1573
- if (isNearInfiniteLimit) {
1574
- timer.error = new Error();
1575
- }
1576
-
1577
- timer.type = timer.immediate ? "Immediate" : "Timeout";
1578
-
1579
- if (timer.hasOwnProperty("delay")) {
1580
- if (typeof timer.delay !== "number") {
1581
- timer.delay = parseInt(timer.delay, 10);
1582
- }
1583
-
1584
- if (!isNumberFinite(timer.delay)) {
1585
- timer.delay = 0;
1586
- }
1587
- timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
1588
- timer.delay = Math.max(0, timer.delay);
1589
- }
1590
-
1591
- if (timer.hasOwnProperty("interval")) {
1592
- timer.type = "Interval";
1593
- timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
1594
- }
1595
-
1596
- if (timer.hasOwnProperty("animation")) {
1597
- timer.type = "AnimationFrame";
1598
- timer.animation = true;
1599
- }
1600
-
1601
- if (timer.hasOwnProperty("idleCallback")) {
1602
- timer.type = "IdleCallback";
1603
- timer.idleCallback = true;
1604
- }
1605
-
1606
- if (!clock.timers) {
1607
- clock.timers = {};
1608
- }
1609
-
1610
- timer.id = uniqueTimerId++;
1611
- timer.createdAt = clock.now;
1612
- timer.callAt =
1613
- clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1614
-
1615
- clock.timers[timer.id] = timer;
1616
-
1617
- if (addTimerReturnsObject) {
1618
- const res = {
1619
- refed: true,
1620
- ref: function () {
1621
- this.refed = true;
1622
- return res;
1623
- },
1624
- unref: function () {
1625
- this.refed = false;
1626
- return res;
1627
- },
1628
- hasRef: function () {
1629
- return this.refed;
1630
- },
1631
- refresh: function () {
1632
- timer.callAt =
1633
- clock.now +
1634
- (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1635
-
1636
- // it _might_ have been removed, but if not the assignment is perfectly fine
1637
- clock.timers[timer.id] = timer;
1638
-
1639
- return res;
1640
- },
1641
- [Symbol.toPrimitive]: function () {
1642
- return timer.id;
1643
- },
1644
- };
1645
- return res;
1646
- }
1647
-
1648
- return timer.id;
1649
- }
1650
-
1651
- /* eslint consistent-return: "off" */
1652
- /**
1653
- * Timer comparitor
1654
- * @param {Timer} a
1655
- * @param {Timer} b
1656
- * @returns {number}
1657
- */
1658
- function compareTimers(a, b) {
1659
- // Sort first by absolute timing
1660
- if (a.callAt < b.callAt) {
1661
- return -1;
1662
- }
1663
- if (a.callAt > b.callAt) {
1664
- return 1;
1665
- }
1666
-
1667
- // Sort next by immediate, immediate timers take precedence
1668
- if (a.immediate && !b.immediate) {
1669
- return -1;
1670
- }
1671
- if (!a.immediate && b.immediate) {
1672
- return 1;
1673
- }
1674
-
1675
- // Sort next by creation time, earlier-created timers take precedence
1676
- if (a.createdAt < b.createdAt) {
1677
- return -1;
1678
- }
1679
- if (a.createdAt > b.createdAt) {
1680
- return 1;
1681
- }
1682
-
1683
- // Sort next by id, lower-id timers take precedence
1684
- if (a.id < b.id) {
1685
- return -1;
1686
- }
1687
- if (a.id > b.id) {
1688
- return 1;
1689
- }
1690
-
1691
- // As timer ids are unique, no fallback `0` is necessary
1692
- }
1693
-
1694
- /**
1695
- * @param {Clock} clock
1696
- * @param {number} from
1697
- * @param {number} to
1698
- * @returns {Timer}
1699
- */
1700
- function firstTimerInRange(clock, from, to) {
1701
- const timers = clock.timers;
1702
- let timer = null;
1703
- let id, isInRange;
1704
-
1705
- for (id in timers) {
1706
- if (timers.hasOwnProperty(id)) {
1707
- isInRange = inRange(from, to, timers[id]);
1708
-
1709
- if (
1710
- isInRange &&
1711
- (!timer || compareTimers(timer, timers[id]) === 1)
1712
- ) {
1713
- timer = timers[id];
1714
- }
1715
- }
1716
- }
1717
-
1718
- return timer;
1719
- }
1720
-
1721
- /**
1722
- * @param {Clock} clock
1723
- * @returns {Timer}
1724
- */
1725
- function firstTimer(clock) {
1726
- const timers = clock.timers;
1727
- let timer = null;
1728
- let id;
1729
-
1730
- for (id in timers) {
1731
- if (timers.hasOwnProperty(id)) {
1732
- if (!timer || compareTimers(timer, timers[id]) === 1) {
1733
- timer = timers[id];
1734
- }
1735
- }
1736
- }
1737
-
1738
- return timer;
1739
- }
1740
-
1741
- /**
1742
- * @param {Clock} clock
1743
- * @returns {Timer}
1744
- */
1745
- function lastTimer(clock) {
1746
- const timers = clock.timers;
1747
- let timer = null;
1748
- let id;
1749
-
1750
- for (id in timers) {
1751
- if (timers.hasOwnProperty(id)) {
1752
- if (!timer || compareTimers(timer, timers[id]) === -1) {
1753
- timer = timers[id];
1754
- }
1755
- }
1756
- }
1757
-
1758
- return timer;
1759
- }
1760
-
1761
- /**
1762
- * @param {Clock} clock
1763
- * @param {Timer} timer
1764
- */
1765
- function callTimer(clock, timer) {
1766
- if (typeof timer.interval === "number") {
1767
- clock.timers[timer.id].callAt += timer.interval;
1768
- } else {
1769
- delete clock.timers[timer.id];
1770
- }
1771
-
1772
- if (typeof timer.func === "function") {
1773
- timer.func.apply(null, timer.args);
1774
- } else {
1775
- /* eslint no-eval: "off" */
1776
- const eval2 = eval;
1777
- (function () {
1778
- eval2(timer.func);
1779
- })();
1780
- }
1781
- }
1782
-
1783
- /**
1784
- * Gets clear handler name for a given timer type
1785
- * @param {string} ttype
1786
- */
1787
- function getClearHandler(ttype) {
1788
- if (ttype === "IdleCallback" || ttype === "AnimationFrame") {
1789
- return `cancel${ttype}`;
1790
- }
1791
- return `clear${ttype}`;
1792
- }
1793
-
1794
- /**
1795
- * Gets schedule handler name for a given timer type
1796
- * @param {string} ttype
1797
- */
1798
- function getScheduleHandler(ttype) {
1799
- if (ttype === "IdleCallback" || ttype === "AnimationFrame") {
1800
- return `request${ttype}`;
1801
- }
1802
- return `set${ttype}`;
1803
- }
1804
-
1805
- /**
1806
- * Creates an anonymous function to warn only once
1807
- */
1808
- function createWarnOnce() {
1809
- let calls = 0;
1810
- return function (msg) {
1811
- // eslint-disable-next-line
1812
- !calls++ && console.warn(msg);
1813
- };
1814
- }
1815
- const warnOnce = createWarnOnce();
1816
-
1817
- /**
1818
- * @param {Clock} clock
1819
- * @param {number} timerId
1820
- * @param {string} ttype
1821
- */
1822
- function clearTimer(clock, timerId, ttype) {
1823
- if (!timerId) {
1824
- // null appears to be allowed in most browsers, and appears to be
1825
- // relied upon by some libraries, like Bootstrap carousel
1826
- return;
1827
- }
1828
-
1829
- if (!clock.timers) {
1830
- clock.timers = {};
1831
- }
1832
-
1833
- // in Node, the ID is stored as the primitive value for `Timeout` objects
1834
- // for `Immediate` objects, no ID exists, so it gets coerced to NaN
1835
- const id = Number(timerId);
1836
-
1837
- if (Number.isNaN(id) || id < idCounterStart) {
1838
- const handlerName = getClearHandler(ttype);
1839
-
1840
- if (clock.shouldClearNativeTimers === true) {
1841
- const nativeHandler = clock[`_${handlerName}`];
1842
- return typeof nativeHandler === "function"
1843
- ? nativeHandler(timerId)
1844
- : undefined;
1845
- }
1846
- warnOnce(
1847
- `FakeTimers: ${handlerName} was invoked to clear a native timer instead of one created by this library.` +
1848
- "\nTo automatically clean-up native timers, use `shouldClearNativeTimers`.",
1849
- );
1850
- }
1851
-
1852
- if (clock.timers.hasOwnProperty(id)) {
1853
- // check that the ID matches a timer of the correct type
1854
- const timer = clock.timers[id];
1855
- if (
1856
- timer.type === ttype ||
1857
- (timer.type === "Timeout" && ttype === "Interval") ||
1858
- (timer.type === "Interval" && ttype === "Timeout")
1859
- ) {
1860
- delete clock.timers[id];
1861
- } else {
1862
- const clear = getClearHandler(ttype);
1863
- const schedule = getScheduleHandler(timer.type);
1864
- throw new Error(
1865
- `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`,
1866
- );
1867
- }
1868
- }
1869
- }
1870
-
1871
- /**
1872
- * @param {Clock} clock
1873
- * @returns {Timer[]}
1874
- */
1875
- function uninstall(clock) {
1876
- let method, i, l;
1877
- const installedHrTime = "_hrtime";
1878
- const installedNextTick = "_nextTick";
1879
-
1880
- for (i = 0, l = clock.methods.length; i < l; i++) {
1881
- method = clock.methods[i];
1882
- if (method === "hrtime" && _global.process) {
1883
- _global.process.hrtime = clock[installedHrTime];
1884
- } else if (method === "nextTick" && _global.process) {
1885
- _global.process.nextTick = clock[installedNextTick];
1886
- } else if (method === "performance") {
1887
- const originalPerfDescriptor = Object.getOwnPropertyDescriptor(
1888
- clock,
1889
- `_${method}`,
1890
- );
1891
- if (
1892
- originalPerfDescriptor &&
1893
- originalPerfDescriptor.get &&
1894
- !originalPerfDescriptor.set
1895
- ) {
1896
- Object.defineProperty(
1897
- _global,
1898
- method,
1899
- originalPerfDescriptor,
1900
- );
1901
- } else if (originalPerfDescriptor.configurable) {
1902
- _global[method] = clock[`_${method}`];
1903
- }
1904
- } else {
1905
- if (_global[method] && _global[method].hadOwnProperty) {
1906
- _global[method] = clock[`_${method}`];
1907
- } else {
1908
- try {
1909
- delete _global[method];
1910
- } catch (ignore) {
1911
- /* eslint no-empty: "off" */
1912
- }
1913
- }
1914
- }
1915
- if (clock.timersModuleMethods !== undefined) {
1916
- for (let j = 0; j < clock.timersModuleMethods.length; j++) {
1917
- const entry = clock.timersModuleMethods[j];
1918
- timersModule[entry.methodName] = entry.original;
1919
- }
1920
- }
1921
- if (clock.timersPromisesModuleMethods !== undefined) {
1922
- for (
1923
- let j = 0;
1924
- j < clock.timersPromisesModuleMethods.length;
1925
- j++
1926
- ) {
1927
- const entry = clock.timersPromisesModuleMethods[j];
1928
- timersPromisesModule[entry.methodName] = entry.original;
1929
- }
1930
- }
1931
- }
1932
-
1933
- clock.setTickMode("manual");
1934
-
1935
- // Prevent multiple executions which will completely remove these props
1936
- clock.methods = [];
1937
-
1938
- for (const [listener, signal] of clock.abortListenerMap.entries()) {
1939
- signal.removeEventListener("abort", listener);
1940
- clock.abortListenerMap.delete(listener);
1941
- }
1942
-
1943
- // return pending timers, to enable checking what timers remained on uninstall
1944
- if (!clock.timers) {
1945
- return [];
1946
- }
1947
- return Object.keys(clock.timers).map(function mapper(key) {
1948
- return clock.timers[key];
1949
- });
1950
- }
1951
-
1952
- /**
1953
- * @param {object} target the target containing the method to replace
1954
- * @param {string} method the keyname of the method on the target
1955
- * @param {Clock} clock
1956
- */
1957
- function hijackMethod(target, method, clock) {
1958
- clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(
1959
- target,
1960
- method,
1961
- );
1962
- clock[`_${method}`] = target[method];
1963
-
1964
- if (method === "Date") {
1965
- target[method] = clock[method];
1966
- } else if (method === "Intl") {
1967
- target[method] = clock[method];
1968
- } else if (method === "performance") {
1969
- const originalPerfDescriptor = Object.getOwnPropertyDescriptor(
1970
- target,
1971
- method,
1972
- );
1973
- // JSDOM has a read only performance field so we have to save/copy it differently
1974
- if (
1975
- originalPerfDescriptor &&
1976
- originalPerfDescriptor.get &&
1977
- !originalPerfDescriptor.set
1978
- ) {
1979
- Object.defineProperty(
1980
- clock,
1981
- `_${method}`,
1982
- originalPerfDescriptor,
1983
- );
1984
-
1985
- const perfDescriptor = Object.getOwnPropertyDescriptor(
1986
- clock,
1987
- method,
1988
- );
1989
- Object.defineProperty(target, method, perfDescriptor);
1990
- } else {
1991
- target[method] = clock[method];
1992
- }
1993
- } else {
1994
- target[method] = function () {
1995
- return clock[method].apply(clock, arguments);
1996
- };
1997
-
1998
- Object.defineProperties(
1999
- target[method],
2000
- Object.getOwnPropertyDescriptors(clock[method]),
2001
- );
2002
- }
2003
-
2004
- target[method].clock = clock;
2005
- }
2006
-
2007
- /**
2008
- * @param {Clock} clock
2009
- * @param {number} advanceTimeDelta
2010
- */
2011
- function doIntervalTick(clock, advanceTimeDelta) {
2012
- clock.tick(advanceTimeDelta);
2013
- }
2014
-
2015
- /**
2016
- * @typedef {object} Timers
2017
- * @property {setTimeout} setTimeout
2018
- * @property {clearTimeout} clearTimeout
2019
- * @property {setInterval} setInterval
2020
- * @property {clearInterval} clearInterval
2021
- * @property {Date} Date
2022
- * @property {Intl} Intl
2023
- * @property {SetImmediate=} setImmediate
2024
- * @property {function(NodeImmediate): void=} clearImmediate
2025
- * @property {function(number[]):number[]=} hrtime
2026
- * @property {NextTick=} nextTick
2027
- * @property {Performance=} performance
2028
- * @property {RequestAnimationFrame=} requestAnimationFrame
2029
- * @property {boolean=} queueMicrotask
2030
- * @property {function(number): void=} cancelAnimationFrame
2031
- * @property {RequestIdleCallback=} requestIdleCallback
2032
- * @property {function(number): void=} cancelIdleCallback
2033
- */
2034
-
2035
- /** @type {Timers} */
2036
- const timers = {
2037
- setTimeout: _global.setTimeout,
2038
- clearTimeout: _global.clearTimeout,
2039
- setInterval: _global.setInterval,
2040
- clearInterval: _global.clearInterval,
2041
- Date: _global.Date,
2042
- };
2043
-
2044
- if (isPresent.setImmediate) {
2045
- timers.setImmediate = _global.setImmediate;
2046
- }
2047
-
2048
- if (isPresent.clearImmediate) {
2049
- timers.clearImmediate = _global.clearImmediate;
2050
- }
2051
-
2052
- if (isPresent.hrtime) {
2053
- timers.hrtime = _global.process.hrtime;
2054
- }
2055
-
2056
- if (isPresent.nextTick) {
2057
- timers.nextTick = _global.process.nextTick;
2058
- }
2059
-
2060
- if (isPresent.performance) {
2061
- timers.performance = _global.performance;
2062
- }
2063
-
2064
- if (isPresent.requestAnimationFrame) {
2065
- timers.requestAnimationFrame = _global.requestAnimationFrame;
2066
- }
2067
-
2068
- if (isPresent.queueMicrotask) {
2069
- timers.queueMicrotask = _global.queueMicrotask;
2070
- }
2071
-
2072
- if (isPresent.cancelAnimationFrame) {
2073
- timers.cancelAnimationFrame = _global.cancelAnimationFrame;
2074
- }
2075
-
2076
- if (isPresent.requestIdleCallback) {
2077
- timers.requestIdleCallback = _global.requestIdleCallback;
2078
- }
2079
-
2080
- if (isPresent.cancelIdleCallback) {
2081
- timers.cancelIdleCallback = _global.cancelIdleCallback;
2082
- }
2083
-
2084
- if (isPresent.Intl) {
2085
- timers.Intl = NativeIntl;
2086
- }
2087
-
2088
- const originalSetTimeout = _global.setImmediate || _global.setTimeout;
2089
- const originalClearInterval = _global.clearInterval;
2090
- const originalSetInterval = _global.setInterval;
2091
-
2092
- /**
2093
- * @param {Date|number} [start] the system time - non-integer values are floored
2094
- * @param {number} [loopLimit] maximum number of timers that will be run when calling runAll()
2095
- * @returns {Clock}
2096
- */
2097
- function createClock(start, loopLimit) {
2098
- // eslint-disable-next-line no-param-reassign
2099
- start = Math.floor(getEpoch(start));
2100
- // eslint-disable-next-line no-param-reassign
2101
- loopLimit = loopLimit || 1000;
2102
- let nanos = 0;
2103
- const adjustedSystemTime = [0, 0]; // [millis, nanoremainder]
2104
-
2105
- const clock = {
2106
- now: start,
2107
- Date: createDate(),
2108
- loopLimit: loopLimit,
2109
- tickMode: { mode: "manual", counter: 0, delta: undefined },
2110
- };
2111
-
2112
- clock.Date.clock = clock;
2113
-
2114
- //eslint-disable-next-line jsdoc/require-jsdoc
2115
- function getTimeToNextFrame() {
2116
- return 16 - ((clock.now - start) % 16);
2117
- }
2118
-
2119
- //eslint-disable-next-line jsdoc/require-jsdoc
2120
- function hrtime(prev) {
2121
- const millisSinceStart = clock.now - adjustedSystemTime[0] - start;
2122
- const secsSinceStart = Math.floor(millisSinceStart / 1000);
2123
- const remainderInNanos =
2124
- (millisSinceStart - secsSinceStart * 1e3) * 1e6 +
2125
- nanos -
2126
- adjustedSystemTime[1];
2127
-
2128
- if (Array.isArray(prev)) {
2129
- if (prev[1] > 1e9) {
2130
- throw new TypeError(
2131
- "Number of nanoseconds can't exceed a billion",
2132
- );
2133
- }
2134
-
2135
- const oldSecs = prev[0];
2136
- let nanoDiff = remainderInNanos - prev[1];
2137
- let secDiff = secsSinceStart - oldSecs;
2138
-
2139
- if (nanoDiff < 0) {
2140
- nanoDiff += 1e9;
2141
- secDiff -= 1;
2142
- }
2143
-
2144
- return [secDiff, nanoDiff];
2145
- }
2146
- return [secsSinceStart, remainderInNanos];
2147
- }
2148
-
2149
- /**
2150
- * A high resolution timestamp in milliseconds.
2151
- * @typedef {number} DOMHighResTimeStamp
2152
- */
2153
-
2154
- /**
2155
- * performance.now()
2156
- * @returns {DOMHighResTimeStamp}
2157
- */
2158
- function fakePerformanceNow() {
2159
- const hrt = hrtime();
2160
- const millis = hrt[0] * 1000 + hrt[1] / 1e6;
2161
- return millis;
2162
- }
2163
-
2164
- if (isPresent.hrtimeBigint) {
2165
- hrtime.bigint = function () {
2166
- const parts = hrtime();
2167
- return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]); // eslint-disable-line
2168
- };
2169
- }
2170
-
2171
- if (isPresent.Intl) {
2172
- clock.Intl = createIntl();
2173
- clock.Intl.clock = clock;
2174
- }
2175
-
2176
- /**
2177
- * @param {TimerTickMode} tickModeConfig - The new configuration for how the clock should tick.
2178
- */
2179
- clock.setTickMode = function (tickModeConfig) {
2180
- const { mode: newMode, delta: newDelta } = tickModeConfig;
2181
- const { mode: oldMode, delta: oldDelta } = clock.tickMode;
2182
- if (newMode === oldMode && newDelta === oldDelta) {
2183
- return;
2184
- }
2185
-
2186
- if (oldMode === "interval") {
2187
- originalClearInterval(clock.attachedInterval);
2188
- }
2189
-
2190
- clock.tickMode = {
2191
- counter: clock.tickMode.counter + 1,
2192
- mode: newMode,
2193
- delta: newDelta,
2194
- };
2195
-
2196
- if (newMode === "nextAsync") {
2197
- advanceUntilModeChanges();
2198
- } else if (newMode === "interval") {
2199
- createIntervalTick(clock, newDelta || 20);
2200
- }
2201
- };
2202
-
2203
- async function advanceUntilModeChanges() {
2204
- async function newMacrotask() {
2205
- // MessageChannel ensures that setTimeout is not throttled to 4ms.
2206
- // https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified
2207
- // https://stackblitz.com/edit/stackblitz-starters-qtlpcc
2208
- const channel = new MessageChannel();
2209
- await new Promise((resolve) => {
2210
- channel.port1.onmessage = () => {
2211
- resolve();
2212
- channel.port1.close();
2213
- };
2214
- channel.port2.postMessage(undefined);
2215
- });
2216
- channel.port1.close();
2217
- channel.port2.close();
2218
- // setTimeout ensures microtask queue is emptied
2219
- await new Promise((resolve) => {
2220
- originalSetTimeout(resolve);
2221
- });
2222
- }
2223
-
2224
- const { counter } = clock.tickMode;
2225
- while (clock.tickMode.counter === counter) {
2226
- await newMacrotask();
2227
- if (clock.tickMode.counter !== counter) {
2228
- return;
2229
- }
2230
- clock.next();
2231
- }
2232
- }
2233
-
2234
- function pauseAutoTickUntilFinished(promise) {
2235
- if (clock.tickMode.mode !== "nextAsync") {
2236
- return promise;
2237
- }
2238
- clock.setTickMode({ mode: "manual" });
2239
- return promise.finally(() => {
2240
- clock.setTickMode({ mode: "nextAsync" });
2241
- });
2242
- }
2243
-
2244
- clock.requestIdleCallback = function requestIdleCallback(
2245
- func,
2246
- timeout,
2247
- ) {
2248
- let timeToNextIdlePeriod = 0;
2249
-
2250
- if (clock.countTimers() > 0) {
2251
- timeToNextIdlePeriod = 50; // const for now
2252
- }
2253
-
2254
- const result = addTimer(clock, {
2255
- func: func,
2256
- args: Array.prototype.slice.call(arguments, 2),
2257
- delay:
2258
- typeof timeout === "undefined"
2259
- ? timeToNextIdlePeriod
2260
- : Math.min(timeout, timeToNextIdlePeriod),
2261
- idleCallback: true,
2262
- });
2263
-
2264
- return Number(result);
2265
- };
2266
-
2267
- clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
2268
- return clearTimer(clock, timerId, "IdleCallback");
2269
- };
2270
-
2271
- clock.setTimeout = function setTimeout(func, timeout) {
2272
- return addTimer(clock, {
2273
- func: func,
2274
- args: Array.prototype.slice.call(arguments, 2),
2275
- delay: timeout,
2276
- });
2277
- };
2278
- if (typeof _global.Promise !== "undefined" && utilPromisify) {
2279
- clock.setTimeout[utilPromisify.custom] =
2280
- function promisifiedSetTimeout(timeout, arg) {
2281
- return new _global.Promise(function setTimeoutExecutor(
2282
- resolve,
2283
- ) {
2284
- addTimer(clock, {
2285
- func: resolve,
2286
- args: [arg],
2287
- delay: timeout,
2288
- });
2289
- });
2290
- };
2291
- }
2292
-
2293
- clock.clearTimeout = function clearTimeout(timerId) {
2294
- return clearTimer(clock, timerId, "Timeout");
2295
- };
2296
-
2297
- clock.nextTick = function nextTick(func) {
2298
- return enqueueJob(clock, {
2299
- func: func,
2300
- args: Array.prototype.slice.call(arguments, 1),
2301
- error: isNearInfiniteLimit ? new Error() : null,
2302
- });
2303
- };
2304
-
2305
- clock.queueMicrotask = function queueMicrotask(func) {
2306
- return clock.nextTick(func); // explicitly drop additional arguments
2307
- };
2308
-
2309
- clock.setInterval = function setInterval(func, timeout) {
2310
- // eslint-disable-next-line no-param-reassign
2311
- timeout = parseInt(timeout, 10);
2312
- return addTimer(clock, {
2313
- func: func,
2314
- args: Array.prototype.slice.call(arguments, 2),
2315
- delay: timeout,
2316
- interval: timeout,
2317
- });
2318
- };
2319
-
2320
- clock.clearInterval = function clearInterval(timerId) {
2321
- return clearTimer(clock, timerId, "Interval");
2322
- };
2323
-
2324
- if (isPresent.setImmediate) {
2325
- clock.setImmediate = function setImmediate(func) {
2326
- return addTimer(clock, {
2327
- func: func,
2328
- args: Array.prototype.slice.call(arguments, 1),
2329
- immediate: true,
2330
- });
2331
- };
2332
-
2333
- if (typeof _global.Promise !== "undefined" && utilPromisify) {
2334
- clock.setImmediate[utilPromisify.custom] =
2335
- function promisifiedSetImmediate(arg) {
2336
- return new _global.Promise(
2337
- function setImmediateExecutor(resolve) {
2338
- addTimer(clock, {
2339
- func: resolve,
2340
- args: [arg],
2341
- immediate: true,
2342
- });
2343
- },
2344
- );
2345
- };
2346
- }
2347
-
2348
- clock.clearImmediate = function clearImmediate(timerId) {
2349
- return clearTimer(clock, timerId, "Immediate");
2350
- };
2351
- }
2352
-
2353
- clock.countTimers = function countTimers() {
2354
- return (
2355
- Object.keys(clock.timers || {}).length +
2356
- (clock.jobs || []).length
2357
- );
2358
- };
2359
-
2360
- clock.requestAnimationFrame = function requestAnimationFrame(func) {
2361
- const result = addTimer(clock, {
2362
- func: func,
2363
- delay: getTimeToNextFrame(),
2364
- get args() {
2365
- return [fakePerformanceNow()];
2366
- },
2367
- animation: true,
2368
- });
2369
-
2370
- return Number(result);
2371
- };
2372
-
2373
- clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
2374
- return clearTimer(clock, timerId, "AnimationFrame");
2375
- };
2376
-
2377
- clock.runMicrotasks = function runMicrotasks() {
2378
- runJobs(clock);
2379
- };
2380
-
2381
- /**
2382
- * @param {number|string} tickValue milliseconds or a string parseable by parseTime
2383
- * @param {boolean} isAsync
2384
- * @param {Function} resolve
2385
- * @param {Function} reject
2386
- * @returns {number|undefined} will return the new `now` value or nothing for async
2387
- */
2388
- function doTick(tickValue, isAsync, resolve, reject) {
2389
- const msFloat =
2390
- typeof tickValue === "number"
2391
- ? tickValue
2392
- : parseTime(tickValue);
2393
- const ms = Math.floor(msFloat);
2394
- const remainder = nanoRemainder(msFloat);
2395
- let nanosTotal = nanos + remainder;
2396
- let tickTo = clock.now + ms;
2397
-
2398
- if (msFloat < 0) {
2399
- throw new TypeError("Negative ticks are not supported");
2400
- }
2401
-
2402
- // adjust for positive overflow
2403
- if (nanosTotal >= 1e6) {
2404
- tickTo += 1;
2405
- nanosTotal -= 1e6;
2406
- }
2407
-
2408
- nanos = nanosTotal;
2409
- let tickFrom = clock.now;
2410
- let previous = clock.now;
2411
- // ESLint fails to detect this correctly
2412
- /* eslint-disable prefer-const */
2413
- let timer,
2414
- firstException,
2415
- oldNow,
2416
- nextPromiseTick,
2417
- compensationCheck,
2418
- postTimerCall;
2419
- /* eslint-enable prefer-const */
2420
-
2421
- clock.duringTick = true;
2422
-
2423
- // perform microtasks
2424
- oldNow = clock.now;
2425
- runJobs(clock);
2426
- if (oldNow !== clock.now) {
2427
- // compensate for any setSystemTime() call during microtask callback
2428
- tickFrom += clock.now - oldNow;
2429
- tickTo += clock.now - oldNow;
2430
- }
2431
-
2432
- //eslint-disable-next-line jsdoc/require-jsdoc
2433
- function doTickInner() {
2434
- // perform each timer in the requested range
2435
- timer = firstTimerInRange(clock, tickFrom, tickTo);
2436
- // eslint-disable-next-line no-unmodified-loop-condition
2437
- while (timer && tickFrom <= tickTo) {
2438
- if (clock.timers[timer.id]) {
2439
- tickFrom = timer.callAt;
2440
- clock.now = timer.callAt;
2441
- oldNow = clock.now;
2442
- try {
2443
- runJobs(clock);
2444
- callTimer(clock, timer);
2445
- } catch (e) {
2446
- firstException = firstException || e;
2447
- }
2448
-
2449
- if (isAsync) {
2450
- // finish up after native setImmediate callback to allow
2451
- // all native es6 promises to process their callbacks after
2452
- // each timer fires.
2453
- originalSetTimeout(nextPromiseTick);
2454
- return;
2455
- }
2456
-
2457
- compensationCheck();
2458
- }
2459
-
2460
- postTimerCall();
2461
- }
2462
-
2463
- // perform process.nextTick()s again
2464
- oldNow = clock.now;
2465
- runJobs(clock);
2466
- if (oldNow !== clock.now) {
2467
- // compensate for any setSystemTime() call during process.nextTick() callback
2468
- tickFrom += clock.now - oldNow;
2469
- tickTo += clock.now - oldNow;
2470
- }
2471
- clock.duringTick = false;
2472
-
2473
- // corner case: during runJobs new timers were scheduled which could be in the range [clock.now, tickTo]
2474
- timer = firstTimerInRange(clock, tickFrom, tickTo);
2475
- if (timer) {
2476
- try {
2477
- clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range
2478
- } catch (e) {
2479
- firstException = firstException || e;
2480
- }
2481
- } else {
2482
- // no timers remaining in the requested range: move the clock all the way to the end
2483
- clock.now = tickTo;
2484
-
2485
- // update nanos
2486
- nanos = nanosTotal;
2487
- }
2488
- if (firstException) {
2489
- throw firstException;
2490
- }
2491
-
2492
- if (isAsync) {
2493
- resolve(clock.now);
2494
- } else {
2495
- return clock.now;
2496
- }
2497
- }
2498
-
2499
- nextPromiseTick =
2500
- isAsync &&
2501
- function () {
2502
- try {
2503
- compensationCheck();
2504
- postTimerCall();
2505
- doTickInner();
2506
- } catch (e) {
2507
- reject(e);
2508
- }
2509
- };
2510
-
2511
- compensationCheck = function () {
2512
- // compensate for any setSystemTime() call during timer callback
2513
- if (oldNow !== clock.now) {
2514
- tickFrom += clock.now - oldNow;
2515
- tickTo += clock.now - oldNow;
2516
- previous += clock.now - oldNow;
2517
- }
2518
- };
2519
-
2520
- postTimerCall = function () {
2521
- timer = firstTimerInRange(clock, previous, tickTo);
2522
- previous = tickFrom;
2523
- };
2524
-
2525
- return doTickInner();
2526
- }
2527
-
2528
- /**
2529
- * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2530
- * @returns {number} will return the new `now` value
2531
- */
2532
- clock.tick = function tick(tickValue) {
2533
- return doTick(tickValue, false);
2534
- };
2535
-
2536
- if (typeof _global.Promise !== "undefined") {
2537
- /**
2538
- * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2539
- * @returns {Promise}
2540
- */
2541
- clock.tickAsync = function tickAsync(tickValue) {
2542
- return pauseAutoTickUntilFinished(
2543
- new _global.Promise(function (resolve, reject) {
2544
- originalSetTimeout(function () {
2545
- try {
2546
- doTick(tickValue, true, resolve, reject);
2547
- } catch (e) {
2548
- reject(e);
2549
- }
2550
- });
2551
- }),
2552
- );
2553
- };
2554
- }
2555
-
2556
- clock.next = function next() {
2557
- runJobs(clock);
2558
- const timer = firstTimer(clock);
2559
- if (!timer) {
2560
- return clock.now;
2561
- }
2562
-
2563
- clock.duringTick = true;
2564
- try {
2565
- clock.now = timer.callAt;
2566
- callTimer(clock, timer);
2567
- runJobs(clock);
2568
- return clock.now;
2569
- } finally {
2570
- clock.duringTick = false;
2571
- }
2572
- };
2573
-
2574
- if (typeof _global.Promise !== "undefined") {
2575
- clock.nextAsync = function nextAsync() {
2576
- return pauseAutoTickUntilFinished(
2577
- new _global.Promise(function (resolve, reject) {
2578
- originalSetTimeout(function () {
2579
- try {
2580
- const timer = firstTimer(clock);
2581
- if (!timer) {
2582
- resolve(clock.now);
2583
- return;
2584
- }
2585
-
2586
- let err;
2587
- clock.duringTick = true;
2588
- clock.now = timer.callAt;
2589
- try {
2590
- callTimer(clock, timer);
2591
- } catch (e) {
2592
- err = e;
2593
- }
2594
- clock.duringTick = false;
2595
-
2596
- originalSetTimeout(function () {
2597
- if (err) {
2598
- reject(err);
2599
- } else {
2600
- resolve(clock.now);
2601
- }
2602
- });
2603
- } catch (e) {
2604
- reject(e);
2605
- }
2606
- });
2607
- }),
2608
- );
2609
- };
2610
- }
2611
-
2612
- clock.runAll = function runAll() {
2613
- let numTimers, i;
2614
- runJobs(clock);
2615
- for (i = 0; i < clock.loopLimit; i++) {
2616
- if (!clock.timers) {
2617
- resetIsNearInfiniteLimit();
2618
- return clock.now;
2619
- }
2620
-
2621
- numTimers = Object.keys(clock.timers).length;
2622
- if (numTimers === 0) {
2623
- resetIsNearInfiniteLimit();
2624
- return clock.now;
2625
- }
2626
-
2627
- clock.next();
2628
- checkIsNearInfiniteLimit(clock, i);
2629
- }
2630
-
2631
- const excessJob = firstTimer(clock);
2632
- throw getInfiniteLoopError(clock, excessJob);
2633
- };
2634
-
2635
- clock.runToFrame = function runToFrame() {
2636
- return clock.tick(getTimeToNextFrame());
2637
- };
2638
-
2639
- if (typeof _global.Promise !== "undefined") {
2640
- clock.runAllAsync = function runAllAsync() {
2641
- return pauseAutoTickUntilFinished(
2642
- new _global.Promise(function (resolve, reject) {
2643
- let i = 0;
2644
- /**
2645
- *
2646
- */
2647
- function doRun() {
2648
- originalSetTimeout(function () {
2649
- try {
2650
- runJobs(clock);
2651
-
2652
- let numTimers;
2653
- if (i < clock.loopLimit) {
2654
- if (!clock.timers) {
2655
- resetIsNearInfiniteLimit();
2656
- resolve(clock.now);
2657
- return;
2658
- }
2659
-
2660
- numTimers = Object.keys(
2661
- clock.timers,
2662
- ).length;
2663
- if (numTimers === 0) {
2664
- resetIsNearInfiniteLimit();
2665
- resolve(clock.now);
2666
- return;
2667
- }
2668
-
2669
- clock.next();
2670
-
2671
- i++;
2672
-
2673
- doRun();
2674
- checkIsNearInfiniteLimit(clock, i);
2675
- return;
2676
- }
2677
-
2678
- const excessJob = firstTimer(clock);
2679
- reject(
2680
- getInfiniteLoopError(clock, excessJob),
2681
- );
2682
- } catch (e) {
2683
- reject(e);
2684
- }
2685
- });
2686
- }
2687
- doRun();
2688
- }),
2689
- );
2690
- };
2691
- }
2692
-
2693
- clock.runToLast = function runToLast() {
2694
- const timer = lastTimer(clock);
2695
- if (!timer) {
2696
- runJobs(clock);
2697
- return clock.now;
2698
- }
2699
-
2700
- return clock.tick(timer.callAt - clock.now);
2701
- };
2702
-
2703
- if (typeof _global.Promise !== "undefined") {
2704
- clock.runToLastAsync = function runToLastAsync() {
2705
- return pauseAutoTickUntilFinished(
2706
- new _global.Promise(function (resolve, reject) {
2707
- originalSetTimeout(function () {
2708
- try {
2709
- const timer = lastTimer(clock);
2710
- if (!timer) {
2711
- runJobs(clock);
2712
- resolve(clock.now);
2713
- }
2714
-
2715
- resolve(
2716
- clock.tickAsync(timer.callAt - clock.now),
2717
- );
2718
- } catch (e) {
2719
- reject(e);
2720
- }
2721
- });
2722
- }),
2723
- );
2724
- };
2725
- }
2726
-
2727
- clock.reset = function reset() {
2728
- nanos = 0;
2729
- clock.timers = {};
2730
- clock.jobs = [];
2731
- clock.now = start;
2732
- };
2733
-
2734
- clock.setSystemTime = function setSystemTime(systemTime) {
2735
- // determine time difference
2736
- const newNow = getEpoch(systemTime);
2737
- const difference = newNow - clock.now;
2738
- let id, timer;
2739
-
2740
- adjustedSystemTime[0] = adjustedSystemTime[0] + difference;
2741
- adjustedSystemTime[1] = adjustedSystemTime[1] + nanos;
2742
- // update 'system clock'
2743
- clock.now = newNow;
2744
- nanos = 0;
2745
-
2746
- // update timers and intervals to keep them stable
2747
- for (id in clock.timers) {
2748
- if (clock.timers.hasOwnProperty(id)) {
2749
- timer = clock.timers[id];
2750
- timer.createdAt += difference;
2751
- timer.callAt += difference;
2752
- }
2753
- }
2754
- };
2755
-
2756
- /**
2757
- * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2758
- * @returns {number} will return the new `now` value
2759
- */
2760
- clock.jump = function jump(tickValue) {
2761
- const msFloat =
2762
- typeof tickValue === "number"
2763
- ? tickValue
2764
- : parseTime(tickValue);
2765
- const ms = Math.floor(msFloat);
2766
-
2767
- for (const timer of Object.values(clock.timers)) {
2768
- if (clock.now + ms > timer.callAt) {
2769
- timer.callAt = clock.now + ms;
2770
- }
2771
- }
2772
- clock.tick(ms);
2773
- };
2774
-
2775
- if (isPresent.performance) {
2776
- clock.performance = Object.create(null);
2777
- clock.performance.now = fakePerformanceNow;
2778
- }
2779
-
2780
- if (isPresent.hrtime) {
2781
- clock.hrtime = hrtime;
2782
- }
2783
-
2784
- return clock;
2785
- }
2786
-
2787
- function createIntervalTick(clock, delta) {
2788
- const intervalTick = doIntervalTick.bind(null, clock, delta);
2789
- const intervalId = originalSetInterval(intervalTick, delta);
2790
- clock.attachedInterval = intervalId;
2791
- }
2792
-
2793
- /* eslint-disable complexity */
2794
-
2795
- /**
2796
- * @param {Config=} [config] Optional config
2797
- * @returns {Clock}
2798
- */
2799
- function install(config) {
2800
- if (
2801
- arguments.length > 1 ||
2802
- config instanceof Date ||
2803
- Array.isArray(config) ||
2804
- typeof config === "number"
2805
- ) {
2806
- throw new TypeError(
2807
- `FakeTimers.install called with ${String(
2808
- config,
2809
- )} install requires an object parameter`,
2810
- );
2811
- }
2812
-
2813
- if (_global.Date.isFake === true) {
2814
- // Timers are already faked; this is a problem.
2815
- // Make the user reset timers before continuing.
2816
- throw new TypeError(
2817
- "Can't install fake timers twice on the same global object.",
2818
- );
2819
- }
2820
-
2821
- // eslint-disable-next-line no-param-reassign
2822
- config = typeof config !== "undefined" ? config : {};
2823
- config.shouldAdvanceTime = config.shouldAdvanceTime || false;
2824
- config.advanceTimeDelta = config.advanceTimeDelta || 20;
2825
- config.shouldClearNativeTimers =
2826
- config.shouldClearNativeTimers || false;
2827
-
2828
- if (config.target) {
2829
- throw new TypeError(
2830
- "config.target is no longer supported. Use `withGlobal(target)` instead.",
2831
- );
2832
- }
2833
-
2834
- /**
2835
- * @param {string} timer/object the name of the thing that is not present
2836
- * @param timer
2837
- */
2838
- function handleMissingTimer(timer) {
2839
- if (config.ignoreMissingTimers) {
2840
- return;
2841
- }
2842
-
2843
- throw new ReferenceError(
2844
- `non-existent timers and/or objects cannot be faked: '${timer}'`,
2845
- );
2846
- }
2847
-
2848
- let i, l;
2849
- const clock = createClock(config.now, config.loopLimit);
2850
- clock.shouldClearNativeTimers = config.shouldClearNativeTimers;
2851
-
2852
- clock.uninstall = function () {
2853
- return uninstall(clock);
2854
- };
2855
-
2856
- clock.abortListenerMap = new Map();
2857
-
2858
- clock.methods = config.toFake || [];
2859
-
2860
- if (clock.methods.length === 0) {
2861
- clock.methods = Object.keys(timers);
2862
- }
2863
-
2864
- if (config.shouldAdvanceTime === true) {
2865
- clock.setTickMode({
2866
- mode: "interval",
2867
- delta: config.advanceTimeDelta,
2868
- });
2869
- }
2870
-
2871
- if (clock.methods.includes("performance")) {
2872
- const proto = (() => {
2873
- if (hasPerformanceConstructorPrototype) {
2874
- return _global.performance.constructor.prototype;
2875
- }
2876
- if (hasPerformancePrototype) {
2877
- return _global.Performance.prototype;
2878
- }
2879
- })();
2880
- if (proto) {
2881
- Object.getOwnPropertyNames(proto).forEach(function (name) {
2882
- if (name !== "now") {
2883
- clock.performance[name] =
2884
- name.indexOf("getEntries") === 0
2885
- ? NOOP_ARRAY
2886
- : NOOP;
2887
- }
2888
- });
2889
- // ensure `mark` returns a value that is valid
2890
- clock.performance.mark = (name) =>
2891
- new FakePerformanceEntry(name, "mark", 0, 0);
2892
- clock.performance.measure = (name) =>
2893
- new FakePerformanceEntry(name, "measure", 0, 100);
2894
- // `timeOrigin` should return the time of when the Window session started
2895
- // (or the Worker was installed)
2896
- clock.performance.timeOrigin = getEpoch(config.now);
2897
- } else if ((config.toFake || []).includes("performance")) {
2898
- return handleMissingTimer("performance");
2899
- }
2900
- }
2901
- if (_global === globalObject && timersModule) {
2902
- clock.timersModuleMethods = [];
2903
- }
2904
- if (_global === globalObject && timersPromisesModule) {
2905
- clock.timersPromisesModuleMethods = [];
2906
- }
2907
- for (i = 0, l = clock.methods.length; i < l; i++) {
2908
- const nameOfMethodToReplace = clock.methods[i];
2909
-
2910
- if (!isPresent[nameOfMethodToReplace]) {
2911
- handleMissingTimer(nameOfMethodToReplace);
2912
- // eslint-disable-next-line
2913
- continue;
2914
- }
2915
-
2916
- if (nameOfMethodToReplace === "hrtime") {
2917
- if (
2918
- _global.process &&
2919
- typeof _global.process.hrtime === "function"
2920
- ) {
2921
- hijackMethod(_global.process, nameOfMethodToReplace, clock);
2922
- }
2923
- } else if (nameOfMethodToReplace === "nextTick") {
2924
- if (
2925
- _global.process &&
2926
- typeof _global.process.nextTick === "function"
2927
- ) {
2928
- hijackMethod(_global.process, nameOfMethodToReplace, clock);
2929
- }
2930
- } else {
2931
- hijackMethod(_global, nameOfMethodToReplace, clock);
2932
- }
2933
- if (
2934
- clock.timersModuleMethods !== undefined &&
2935
- timersModule[nameOfMethodToReplace]
2936
- ) {
2937
- const original = timersModule[nameOfMethodToReplace];
2938
- clock.timersModuleMethods.push({
2939
- methodName: nameOfMethodToReplace,
2940
- original: original,
2941
- });
2942
- timersModule[nameOfMethodToReplace] =
2943
- _global[nameOfMethodToReplace];
2944
- }
2945
- if (clock.timersPromisesModuleMethods !== undefined) {
2946
- if (nameOfMethodToReplace === "setTimeout") {
2947
- clock.timersPromisesModuleMethods.push({
2948
- methodName: "setTimeout",
2949
- original: timersPromisesModule.setTimeout,
2950
- });
2951
-
2952
- timersPromisesModule.setTimeout = (
2953
- delay,
2954
- value,
2955
- options = {},
2956
- ) =>
2957
- new Promise((resolve, reject) => {
2958
- const abort = () => {
2959
- options.signal.removeEventListener(
2960
- "abort",
2961
- abort,
2962
- );
2963
- clock.abortListenerMap.delete(abort);
2964
-
2965
- // This is safe, there is no code path that leads to this function
2966
- // being invoked before handle has been assigned.
2967
- // eslint-disable-next-line no-use-before-define
2968
- clock.clearTimeout(handle);
2969
- reject(options.signal.reason);
2970
- };
2971
-
2972
- const handle = clock.setTimeout(() => {
2973
- if (options.signal) {
2974
- options.signal.removeEventListener(
2975
- "abort",
2976
- abort,
2977
- );
2978
- clock.abortListenerMap.delete(abort);
2979
- }
2980
-
2981
- resolve(value);
2982
- }, delay);
2983
-
2984
- if (options.signal) {
2985
- if (options.signal.aborted) {
2986
- abort();
2987
- } else {
2988
- options.signal.addEventListener(
2989
- "abort",
2990
- abort,
2991
- );
2992
- clock.abortListenerMap.set(
2993
- abort,
2994
- options.signal,
2995
- );
2996
- }
2997
- }
2998
- });
2999
- } else if (nameOfMethodToReplace === "setImmediate") {
3000
- clock.timersPromisesModuleMethods.push({
3001
- methodName: "setImmediate",
3002
- original: timersPromisesModule.setImmediate,
3003
- });
3004
-
3005
- timersPromisesModule.setImmediate = (value, options = {}) =>
3006
- new Promise((resolve, reject) => {
3007
- const abort = () => {
3008
- options.signal.removeEventListener(
3009
- "abort",
3010
- abort,
3011
- );
3012
- clock.abortListenerMap.delete(abort);
3013
-
3014
- // This is safe, there is no code path that leads to this function
3015
- // being invoked before handle has been assigned.
3016
- // eslint-disable-next-line no-use-before-define
3017
- clock.clearImmediate(handle);
3018
- reject(options.signal.reason);
3019
- };
3020
-
3021
- const handle = clock.setImmediate(() => {
3022
- if (options.signal) {
3023
- options.signal.removeEventListener(
3024
- "abort",
3025
- abort,
3026
- );
3027
- clock.abortListenerMap.delete(abort);
3028
- }
3029
-
3030
- resolve(value);
3031
- });
3032
-
3033
- if (options.signal) {
3034
- if (options.signal.aborted) {
3035
- abort();
3036
- } else {
3037
- options.signal.addEventListener(
3038
- "abort",
3039
- abort,
3040
- );
3041
- clock.abortListenerMap.set(
3042
- abort,
3043
- options.signal,
3044
- );
3045
- }
3046
- }
3047
- });
3048
- } else if (nameOfMethodToReplace === "setInterval") {
3049
- clock.timersPromisesModuleMethods.push({
3050
- methodName: "setInterval",
3051
- original: timersPromisesModule.setInterval,
3052
- });
3053
-
3054
- timersPromisesModule.setInterval = (
3055
- delay,
3056
- value,
3057
- options = {},
3058
- ) => ({
3059
- [Symbol.asyncIterator]: () => {
3060
- const createResolvable = () => {
3061
- let resolve, reject;
3062
- const promise = new Promise((res, rej) => {
3063
- resolve = res;
3064
- reject = rej;
3065
- });
3066
- promise.resolve = resolve;
3067
- promise.reject = reject;
3068
- return promise;
3069
- };
3070
-
3071
- let done = false;
3072
- let hasThrown = false;
3073
- let returnCall;
3074
- let nextAvailable = 0;
3075
- const nextQueue = [];
3076
-
3077
- const handle = clock.setInterval(() => {
3078
- if (nextQueue.length > 0) {
3079
- nextQueue.shift().resolve();
3080
- } else {
3081
- nextAvailable++;
3082
- }
3083
- }, delay);
3084
-
3085
- const abort = () => {
3086
- options.signal.removeEventListener(
3087
- "abort",
3088
- abort,
3089
- );
3090
- clock.abortListenerMap.delete(abort);
3091
-
3092
- clock.clearInterval(handle);
3093
- done = true;
3094
- for (const resolvable of nextQueue) {
3095
- resolvable.resolve();
3096
- }
3097
- };
3098
-
3099
- if (options.signal) {
3100
- if (options.signal.aborted) {
3101
- done = true;
3102
- } else {
3103
- options.signal.addEventListener(
3104
- "abort",
3105
- abort,
3106
- );
3107
- clock.abortListenerMap.set(
3108
- abort,
3109
- options.signal,
3110
- );
3111
- }
3112
- }
3113
-
3114
- return {
3115
- next: async () => {
3116
- if (options.signal?.aborted && !hasThrown) {
3117
- hasThrown = true;
3118
- throw options.signal.reason;
3119
- }
3120
-
3121
- if (done) {
3122
- return { done: true, value: undefined };
3123
- }
3124
-
3125
- if (nextAvailable > 0) {
3126
- nextAvailable--;
3127
- return { done: false, value: value };
3128
- }
3129
-
3130
- const resolvable = createResolvable();
3131
- nextQueue.push(resolvable);
3132
-
3133
- await resolvable;
3134
-
3135
- if (returnCall && nextQueue.length === 0) {
3136
- returnCall.resolve();
3137
- }
3138
-
3139
- if (options.signal?.aborted && !hasThrown) {
3140
- hasThrown = true;
3141
- throw options.signal.reason;
3142
- }
3143
-
3144
- if (done) {
3145
- return { done: true, value: undefined };
3146
- }
3147
-
3148
- return { done: false, value: value };
3149
- },
3150
- return: async () => {
3151
- if (done) {
3152
- return { done: true, value: undefined };
3153
- }
3154
-
3155
- if (nextQueue.length > 0) {
3156
- returnCall = createResolvable();
3157
- await returnCall;
3158
- }
3159
-
3160
- clock.clearInterval(handle);
3161
- done = true;
3162
-
3163
- if (options.signal) {
3164
- options.signal.removeEventListener(
3165
- "abort",
3166
- abort,
3167
- );
3168
- clock.abortListenerMap.delete(abort);
3169
- }
3170
-
3171
- return { done: true, value: undefined };
3172
- },
3173
- };
3174
- },
3175
- });
3176
- }
3177
- }
3178
- }
3179
-
3180
- return clock;
3181
- }
3182
-
3183
- /* eslint-enable complexity */
3184
-
3185
- return {
3186
- timers: timers,
3187
- createClock: createClock,
3188
- install: install,
3189
- withGlobal: withGlobal,
3190
- };
3191
- }
3192
-
3193
- /**
3194
- * @typedef {object} FakeTimers
3195
- * @property {Timers} timers
3196
- * @property {createClock} createClock
3197
- * @property {Function} install
3198
- * @property {withGlobal} withGlobal
3199
- */
3200
-
3201
- /* eslint-enable complexity */
3202
-
3203
- /** @type {FakeTimers} */
3204
- const defaultImplementation = withGlobal(globalObject);
3205
-
3206
- fakeTimersSrc.timers = defaultImplementation.timers;
3207
- fakeTimersSrc.createClock = defaultImplementation.createClock;
3208
- fakeTimersSrc.install = defaultImplementation.install;
3209
- fakeTimersSrc.withGlobal = withGlobal;
3210
- return fakeTimersSrc;
3211
- }
3212
-
3213
- var fakeTimersSrcExports = requireFakeTimersSrc();
3214
-
3215
- class FakeTimers {
3216
- _global;
3217
- _clock;
3218
- // | _fakingTime | _fakingDate |
3219
- // +-------------+-------------+
3220
- // | false | falsy | initial
3221
- // | false | truthy | vi.setSystemTime called first (for mocking only Date without fake timers)
3222
- // | true | falsy | vi.useFakeTimers called first
3223
- // | true | truthy | unreachable
3224
- _fakingTime;
3225
- _fakingDate;
3226
- _fakeTimers;
3227
- _userConfig;
3228
- _now = RealDate.now;
3229
- constructor({ global, config }) {
3230
- this._userConfig = config;
3231
- this._fakingDate = null;
3232
- this._fakingTime = false;
3233
- this._fakeTimers = fakeTimersSrcExports.withGlobal(global);
3234
- this._global = global;
3235
- }
3236
- clearAllTimers() {
3237
- if (this._fakingTime) this._clock.reset();
3238
- }
3239
- dispose() {
3240
- this.useRealTimers();
3241
- }
3242
- runAllTimers() {
3243
- if (this._checkFakeTimers()) this._clock.runAll();
3244
- }
3245
- async runAllTimersAsync() {
3246
- if (this._checkFakeTimers()) await this._clock.runAllAsync();
3247
- }
3248
- runOnlyPendingTimers() {
3249
- if (this._checkFakeTimers()) this._clock.runToLast();
3250
- }
3251
- async runOnlyPendingTimersAsync() {
3252
- if (this._checkFakeTimers()) await this._clock.runToLastAsync();
3253
- }
3254
- advanceTimersToNextTimer(steps = 1) {
3255
- if (this._checkFakeTimers()) for (let i = steps; i > 0; i--) {
3256
- this._clock.next();
3257
- // Fire all timers at this point: https://github.com/sinonjs/fake-timers/issues/250
3258
- this._clock.tick(0);
3259
- if (this._clock.countTimers() === 0) break;
3260
- }
3261
- }
3262
- async advanceTimersToNextTimerAsync(steps = 1) {
3263
- if (this._checkFakeTimers()) for (let i = steps; i > 0; i--) {
3264
- await this._clock.nextAsync();
3265
- // Fire all timers at this point: https://github.com/sinonjs/fake-timers/issues/250
3266
- this._clock.tick(0);
3267
- if (this._clock.countTimers() === 0) break;
3268
- }
3269
- }
3270
- advanceTimersByTime(msToRun) {
3271
- if (this._checkFakeTimers()) this._clock.tick(msToRun);
3272
- }
3273
- async advanceTimersByTimeAsync(msToRun) {
3274
- if (this._checkFakeTimers()) await this._clock.tickAsync(msToRun);
3275
- }
3276
- advanceTimersToNextFrame() {
3277
- if (this._checkFakeTimers()) this._clock.runToFrame();
3278
- }
3279
- runAllTicks() {
3280
- if (this._checkFakeTimers()) this._clock.runMicrotasks();
3281
- }
3282
- useRealTimers() {
3283
- if (this._fakingDate) {
3284
- resetDate();
3285
- this._fakingDate = null;
3286
- }
3287
- if (this._fakingTime) {
3288
- this._clock.uninstall();
3289
- this._fakingTime = false;
3290
- }
3291
- }
3292
- useFakeTimers() {
3293
- const fakeDate = this._fakingDate || Date.now();
3294
- if (this._fakingDate) {
3295
- resetDate();
3296
- this._fakingDate = null;
3297
- }
3298
- if (this._fakingTime) this._clock.uninstall();
3299
- const toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick" && timer !== "queueMicrotask");
3300
- if (this._userConfig?.toFake?.includes("nextTick") && isChildProcess()) throw new Error("process.nextTick cannot be mocked inside child_process");
3301
- this._clock = this._fakeTimers.install({
3302
- now: fakeDate,
3303
- ...this._userConfig,
3304
- toFake: this._userConfig?.toFake || toFake,
3305
- ignoreMissingTimers: true
3306
- });
3307
- this._fakingTime = true;
3308
- }
3309
- reset() {
3310
- if (this._checkFakeTimers()) {
3311
- const { now } = this._clock;
3312
- this._clock.reset();
3313
- this._clock.setSystemTime(now);
3314
- }
3315
- }
3316
- setSystemTime(now) {
3317
- const date = typeof now === "undefined" || now instanceof Date ? now : new Date(now);
3318
- if (this._fakingTime) this._clock.setSystemTime(date);
3319
- else {
3320
- this._fakingDate = date ?? new Date(this.getRealSystemTime());
3321
- mockDate(this._fakingDate);
3322
- }
3323
- }
3324
- getMockedSystemTime() {
3325
- return this._fakingTime ? new Date(this._clock.now) : this._fakingDate;
3326
- }
3327
- getRealSystemTime() {
3328
- return this._now();
3329
- }
3330
- getTimerCount() {
3331
- if (this._checkFakeTimers()) return this._clock.countTimers();
3332
- return 0;
3333
- }
3334
- setTimerTickMode(mode, interval) {
3335
- if (this._checkFakeTimers()) if (mode === "manual") this._clock.setTickMode({ mode: "manual" });
3336
- else if (mode === "nextTimerAsync") this._clock.setTickMode({ mode: "nextAsync" });
3337
- else if (mode === "interval") this._clock.setTickMode({
3338
- mode: "interval",
3339
- delta: interval
3340
- });
3341
- else throw new Error(`Invalid tick mode: ${mode}`);
3342
- }
3343
- configure(config) {
3344
- this._userConfig = config;
3345
- }
3346
- isFakeTimers() {
3347
- return this._fakingTime;
3348
- }
3349
- _checkFakeTimers() {
3350
- if (!this._fakingTime) throw new Error("A function to advance timers was called but the timers APIs are not mocked. Call `vi.useFakeTimers()` in the test file first.");
3351
- return this._fakingTime;
3352
- }
3353
- }
3354
-
3355
- function copyStackTrace$1(target, source) {
3356
- if (source.stack !== void 0) target.stack = source.stack.replace(source.message, target.message);
3357
- return target;
3358
- }
3359
- function waitFor(callback, options = {}) {
3360
- const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
3361
- const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
3362
- const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
3363
- return new Promise((resolve, reject) => {
3364
- let lastError;
3365
- let promiseStatus = "idle";
3366
- let timeoutId;
3367
- let intervalId;
3368
- const onResolve = (result) => {
3369
- if (timeoutId) clearTimeout(timeoutId);
3370
- if (intervalId) clearInterval(intervalId);
3371
- resolve(result);
3372
- };
3373
- const handleTimeout = () => {
3374
- if (intervalId) clearInterval(intervalId);
3375
- let error = lastError;
3376
- if (!error) error = copyStackTrace$1(/* @__PURE__ */ new Error("Timed out in waitFor!"), STACK_TRACE_ERROR);
3377
- reject(error);
3378
- };
3379
- const checkCallback = () => {
3380
- if (vi.isFakeTimers()) vi.advanceTimersByTime(interval);
3381
- if (promiseStatus === "pending") return;
3382
- try {
3383
- const result = callback();
3384
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
3385
- const thenable = result;
3386
- promiseStatus = "pending";
3387
- thenable.then((resolvedValue) => {
3388
- promiseStatus = "resolved";
3389
- onResolve(resolvedValue);
3390
- }, (rejectedValue) => {
3391
- promiseStatus = "rejected";
3392
- lastError = rejectedValue;
3393
- });
3394
- } else {
3395
- onResolve(result);
3396
- return true;
3397
- }
3398
- } catch (error) {
3399
- lastError = error;
3400
- }
3401
- };
3402
- if (checkCallback() === true) return;
3403
- timeoutId = setTimeout(handleTimeout, timeout);
3404
- intervalId = setInterval(checkCallback, interval);
3405
- });
3406
- }
3407
- function waitUntil(callback, options = {}) {
3408
- const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
3409
- const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
3410
- const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
3411
- return new Promise((resolve, reject) => {
3412
- let promiseStatus = "idle";
3413
- let timeoutId;
3414
- let intervalId;
3415
- const onReject = (error) => {
3416
- if (intervalId) clearInterval(intervalId);
3417
- if (!error) error = copyStackTrace$1(/* @__PURE__ */ new Error("Timed out in waitUntil!"), STACK_TRACE_ERROR);
3418
- reject(error);
3419
- };
3420
- const onResolve = (result) => {
3421
- if (!result) return;
3422
- if (timeoutId) clearTimeout(timeoutId);
3423
- if (intervalId) clearInterval(intervalId);
3424
- resolve(result);
3425
- return true;
3426
- };
3427
- const checkCallback = () => {
3428
- if (vi.isFakeTimers()) vi.advanceTimersByTime(interval);
3429
- if (promiseStatus === "pending") return;
3430
- try {
3431
- const result = callback();
3432
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
3433
- const thenable = result;
3434
- promiseStatus = "pending";
3435
- thenable.then((resolvedValue) => {
3436
- promiseStatus = "resolved";
3437
- onResolve(resolvedValue);
3438
- }, (rejectedValue) => {
3439
- promiseStatus = "rejected";
3440
- onReject(rejectedValue);
3441
- });
3442
- } else return onResolve(result);
3443
- } catch (error) {
3444
- onReject(error);
3445
- }
3446
- };
3447
- if (checkCallback() === true) return;
3448
- timeoutId = setTimeout(onReject, timeout);
3449
- intervalId = setInterval(checkCallback, interval);
3450
- });
3451
- }
3452
-
3453
- function createVitest() {
3454
- let _config = null;
3455
- const state = () => getWorkerState();
3456
- let _timers;
3457
- const timers = () => _timers ||= new FakeTimers({
3458
- global: globalThis,
3459
- config: state().config.fakeTimers
3460
- });
3461
- const _stubsGlobal = /* @__PURE__ */ new Map();
3462
- const _stubsEnv = /* @__PURE__ */ new Map();
3463
- const _envBooleans = [
3464
- "PROD",
3465
- "DEV",
3466
- "SSR"
3467
- ];
3468
- const utils = {
3469
- useFakeTimers(config) {
3470
- if (isChildProcess()) {
3471
- if (config?.toFake?.includes("nextTick") || state().config?.fakeTimers?.toFake?.includes("nextTick")) throw new Error("vi.useFakeTimers({ toFake: [\"nextTick\"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.");
3472
- }
3473
- if (config) timers().configure({
3474
- ...state().config.fakeTimers,
3475
- ...config
3476
- });
3477
- else timers().configure(state().config.fakeTimers);
3478
- timers().useFakeTimers();
3479
- return utils;
3480
- },
3481
- isFakeTimers() {
3482
- return timers().isFakeTimers();
3483
- },
3484
- useRealTimers() {
3485
- timers().useRealTimers();
3486
- return utils;
3487
- },
3488
- runOnlyPendingTimers() {
3489
- timers().runOnlyPendingTimers();
3490
- return utils;
3491
- },
3492
- async runOnlyPendingTimersAsync() {
3493
- await timers().runOnlyPendingTimersAsync();
3494
- return utils;
3495
- },
3496
- runAllTimers() {
3497
- timers().runAllTimers();
3498
- return utils;
3499
- },
3500
- async runAllTimersAsync() {
3501
- await timers().runAllTimersAsync();
3502
- return utils;
3503
- },
3504
- runAllTicks() {
3505
- timers().runAllTicks();
3506
- return utils;
3507
- },
3508
- advanceTimersByTime(ms) {
3509
- timers().advanceTimersByTime(ms);
3510
- return utils;
3511
- },
3512
- async advanceTimersByTimeAsync(ms) {
3513
- await timers().advanceTimersByTimeAsync(ms);
3514
- return utils;
3515
- },
3516
- advanceTimersToNextTimer() {
3517
- timers().advanceTimersToNextTimer();
3518
- return utils;
3519
- },
3520
- async advanceTimersToNextTimerAsync() {
3521
- await timers().advanceTimersToNextTimerAsync();
3522
- return utils;
3523
- },
3524
- advanceTimersToNextFrame() {
3525
- timers().advanceTimersToNextFrame();
3526
- return utils;
3527
- },
3528
- getTimerCount() {
3529
- return timers().getTimerCount();
3530
- },
3531
- setSystemTime(time) {
3532
- timers().setSystemTime(time);
3533
- return utils;
3534
- },
3535
- getMockedSystemTime() {
3536
- return timers().getMockedSystemTime();
3537
- },
3538
- getRealSystemTime() {
3539
- return timers().getRealSystemTime();
3540
- },
3541
- clearAllTimers() {
3542
- timers().clearAllTimers();
3543
- return utils;
3544
- },
3545
- setTimerTickMode(mode, interval) {
3546
- timers().setTimerTickMode(mode, interval);
3547
- return utils;
3548
- },
3549
- spyOn,
3550
- fn,
3551
- waitFor,
3552
- waitUntil,
3553
- defineHelper: (fn) => {
3554
- return function __VITEST_HELPER__(...args) {
3555
- const result = fn.apply(this, args);
3556
- if (result && typeof result === "object" && typeof result.then === "function") return (async function __VITEST_HELPER__() {
3557
- return await result;
3558
- })();
3559
- return result;
3560
- };
3561
- },
3562
- hoisted(factory) {
3563
- assertTypes(factory, "\"vi.hoisted\" factory", ["function"]);
3564
- return factory();
3565
- },
3566
- mock(path, factory) {
3567
- if (typeof path !== "string") throw new TypeError(`vi.mock() expects a string path, but received a ${typeof path}`);
3568
- const importer = getImporter("mock");
3569
- _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer, _mocker().getMockContext().callstack)) : factory);
3570
- },
3571
- unmock(path) {
3572
- if (typeof path !== "string") throw new TypeError(`vi.unmock() expects a string path, but received a ${typeof path}`);
3573
- _mocker().queueUnmock(path, getImporter("unmock"));
3574
- },
3575
- doMock(path, factory) {
3576
- if (typeof path !== "string") throw new TypeError(`vi.doMock() expects a string path, but received a ${typeof path}`);
3577
- const importer = getImporter("doMock");
3578
- _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer, _mocker().getMockContext().callstack)) : factory);
3579
- const rv = {};
3580
- if (Symbol.dispose) rv[Symbol.dispose] = () => {
3581
- _mocker().queueUnmock(path, importer);
3582
- };
3583
- return rv;
3584
- },
3585
- doUnmock(path) {
3586
- if (typeof path !== "string") throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`);
3587
- const importer = getImporter("doUnmock");
3588
- _mocker().queueUnmock(path, importer);
3589
- },
3590
- async importActual(path) {
3591
- const importer = getImporter("importActual");
3592
- return _mocker().importActual(path, importer, _mocker().getMockContext().callstack);
3593
- },
3594
- async importMock(path) {
3595
- const importer = getImporter("importMock");
3596
- return _mocker().importMock(path, importer);
3597
- },
3598
- mockObject(value, options) {
3599
- return _mocker().mockObject({ value }, void 0, options?.spy ? "autospy" : "automock").value;
3600
- },
3601
- mocked(item, _options = {}) {
3602
- return item;
3603
- },
3604
- isMockFunction(fn) {
3605
- return isMockFunction(fn);
3606
- },
3607
- clearAllMocks() {
3608
- clearAllMocks();
3609
- return utils;
3610
- },
3611
- resetAllMocks() {
3612
- resetAllMocks();
3613
- return utils;
3614
- },
3615
- restoreAllMocks() {
3616
- restoreAllMocks();
3617
- return utils;
3618
- },
3619
- stubGlobal(name, value) {
3620
- if (!_stubsGlobal.has(name)) _stubsGlobal.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
3621
- Object.defineProperty(globalThis, name, {
3622
- value,
3623
- writable: true,
3624
- configurable: true,
3625
- enumerable: true
3626
- });
3627
- return utils;
3628
- },
3629
- stubEnv(name, value) {
3630
- const env = state().metaEnv;
3631
- if (!_stubsEnv.has(name)) _stubsEnv.set(name, env[name]);
3632
- if (_envBooleans.includes(name)) env[name] = value ? "1" : "";
3633
- else if (value === void 0) delete env[name];
3634
- else env[name] = String(value);
3635
- return utils;
3636
- },
3637
- unstubAllGlobals() {
3638
- _stubsGlobal.forEach((original, name) => {
3639
- if (!original) Reflect.deleteProperty(globalThis, name);
3640
- else Object.defineProperty(globalThis, name, original);
3641
- });
3642
- _stubsGlobal.clear();
3643
- return utils;
3644
- },
3645
- unstubAllEnvs() {
3646
- const env = state().metaEnv;
3647
- _stubsEnv.forEach((original, name) => {
3648
- if (original === void 0) delete env[name];
3649
- else env[name] = original;
3650
- });
3651
- _stubsEnv.clear();
3652
- return utils;
3653
- },
3654
- resetModules() {
3655
- resetModules(state().evaluatedModules);
3656
- return utils;
3657
- },
3658
- async dynamicImportSettled() {
3659
- return waitForImportsToResolve();
3660
- },
3661
- setConfig(config) {
3662
- if (!_config) _config = { ...state().config };
3663
- Object.assign(state().config, config);
3664
- },
3665
- resetConfig() {
3666
- if (_config) Object.assign(state().config, _config);
3667
- }
3668
- };
3669
- return utils;
3670
- }
3671
- const vitest = createVitest();
3672
- const vi = vitest;
3673
- function _mocker() {
3674
- // @ts-expect-error injected by vite-nide
3675
- return typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : new Proxy({}, { get(_, name) {
3676
- throw new Error(`Vitest mocker was not initialized in this environment. vi.${String(name)}() is forbidden.`);
3677
- } });
3678
- }
3679
- function getImporter(name) {
3680
- const stackArray = createSimpleStackTrace({ stackTraceLimit: 5 }).split("\n");
3681
- return parseSingleStack(stackArray[stackArray.findLastIndex((stack) => {
3682
- return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`) || stack.includes(` at ${name} (`);
3683
- }) + 1])?.file || "";
3684
- }
3685
-
3686
- // these matchers are not supported because they don't make sense with poll
3687
- const unsupported = [
3688
- "matchSnapshot",
3689
- "toMatchSnapshot",
3690
- "toMatchInlineSnapshot",
3691
- "toThrowErrorMatchingSnapshot",
3692
- "toThrowErrorMatchingInlineSnapshot",
3693
- "throws",
3694
- "Throw",
3695
- "throw",
3696
- "toThrow",
3697
- "toThrowError"
3698
- ];
3699
- /**
3700
- * Attaches a `cause` property to the error if missing, copies the stack trace from the source, and throws.
3701
- *
3702
- * @param error - The error to throw
3703
- * @param source - Error to copy the stack trace from
3704
- *
3705
- * @throws Always throws the provided error with an amended stack trace
3706
- */
3707
- function throwWithCause(error, source) {
3708
- if (error.cause == null) error.cause = /* @__PURE__ */ new Error("Matcher did not succeed in time.");
3709
- throw copyStackTrace(error, source);
3710
- }
3711
- function createExpectPoll(expect) {
3712
- return function poll(fn, options = {}) {
3713
- const defaults = getWorkerState().config.expect?.poll ?? {};
3714
- const { interval = defaults.interval ?? 50, timeout = defaults.timeout ?? 1e3, message } = options;
3715
- // @ts-expect-error private poll access
3716
- const assertion = expect(null, message).withContext({ poll: true });
3717
- fn = fn.bind(assertion);
3718
- // injected so that domain snapshot can take over poll implementation.
3719
- chai.util.flag(assertion, "_poll.fn", fn);
3720
- chai.util.flag(assertion, "_poll.timeout", timeout);
3721
- chai.util.flag(assertion, "_poll.interval", interval);
3722
- const test = chai.util.flag(assertion, "vitest-test");
3723
- if (!test) throw new Error("expect.poll() must be called inside a test");
3724
- const proxy = new Proxy(assertion, { get(target, key, receiver) {
3725
- const assertionFunction = Reflect.get(target, key, receiver);
3726
- if (typeof assertionFunction !== "function") return assertionFunction instanceof chai.Assertion ? proxy : assertionFunction;
3727
- if (key === "assert") return assertionFunction;
3728
- if (typeof key === "string" && unsupported.includes(key)) throw new SyntaxError(`expect.poll() is not supported in combination with .${key}(). Use vi.waitFor() if your assertion condition is unstable.`);
3729
- // Core poll stack-trace trick:
3730
- // 1. capture STACK_TRACE_ERROR here before entering the async poll loop
3731
- // 2. when the matcher eventually fails, rethrow via throwWithCause()
3732
- // so the final error keeps this earlier stack
3733
- //
3734
- // For example, when user writes:
3735
- // await expect.poll(...).toBeSomething()
3736
- // STACK_TRACE_ERROR.stack would look like
3737
- // at ...(more internal stacks)...
3738
- // at __VITEST_POLL_CHAIN__ .../packages/vitest/dist/...
3739
- // at .../my-file.test.ts:12:3 (this points to `toBeSomething()` callsite in user test file)
3740
- // Vitest later filters out internal stacks from `vitest/dist`, so the reported errors correctly
3741
- // points to the user callsite for poll assertion errors.
3742
- //
3743
- // Inline snapshots piggyback on the same idea. We pass
3744
- // STACK_TRACE_ERROR through `chai.util.flag(assertion, 'error', ...)`.
3745
- // Inline snapshot assertion access the same error stack for
3746
- // extracting inline snapshot location to validate and update new snapshots.
3747
- return function __VITEST_POLL_CHAIN__(...args) {
3748
- const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
3749
- const promise = async () => {
3750
- chai.util.flag(assertion, "_name", key);
3751
- chai.util.flag(assertion, "error", STACK_TRACE_ERROR);
3752
- const onSettled = chai.util.flag(assertion, "_poll.onSettled");
3753
- if (Object.getOwnPropertyDescriptor(assertionFunction, "__vitest_poll_takeover__")?.value) try {
3754
- const output = await assertionFunction.call(assertion, ...args);
3755
- await onSettled?.({
3756
- assertion,
3757
- status: "pass"
3758
- });
3759
- return output;
3760
- } catch (err) {
3761
- await onSettled?.({
3762
- assertion,
3763
- status: "fail"
3764
- });
3765
- throwWithCause(err, STACK_TRACE_ERROR);
3766
- }
3767
- const { setTimeout, clearTimeout } = getSafeTimers();
3768
- let executionPhase = "fn";
3769
- let hasTimedOut = false;
3770
- const timerId = setTimeout(() => {
3771
- hasTimedOut = true;
3772
- }, timeout);
3773
- try {
3774
- while (true) {
3775
- const isLastAttempt = hasTimedOut;
3776
- if (isLastAttempt) chai.util.flag(assertion, "_isLastPollAttempt", true);
3777
- try {
3778
- executionPhase = "fn";
3779
- const obj = await fn();
3780
- chai.util.flag(assertion, "object", obj);
3781
- executionPhase = "assertion";
3782
- const output = await assertionFunction.call(assertion, ...args);
3783
- await onSettled?.({
3784
- assertion,
3785
- status: "pass"
3786
- });
3787
- return output;
3788
- } catch (err) {
3789
- if (isLastAttempt || executionPhase === "assertion" && chai.util.flag(assertion, "_poll.assert_once")) {
3790
- await onSettled?.({
3791
- assertion,
3792
- status: "fail"
3793
- });
3794
- throwWithCause(err, STACK_TRACE_ERROR);
3795
- }
3796
- await delay(interval, setTimeout);
3797
- if (vi.isFakeTimers()) vi.advanceTimersByTime(interval);
3798
- }
3799
- }
3800
- } finally {
3801
- clearTimeout(timerId);
3802
- }
3803
- };
3804
- let awaited = false;
3805
- test.onFinished ??= [];
3806
- test.onFinished.push(() => {
3807
- if (!awaited) {
3808
- const negated = chai.util.flag(assertion, "negate") ? "not." : "";
3809
- const assertionString = `expect.${chai.util.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)"}.${negated}${String(key)}()`;
3810
- throw copyStackTrace(/* @__PURE__ */ 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`), STACK_TRACE_ERROR);
3811
- }
3812
- });
3813
- let resultPromise;
3814
- // only .then is enough to check awaited, but we type this as `Promise<void>` in global types
3815
- // so let's follow it
3816
- return {
3817
- then(onFulfilled, onRejected) {
3818
- awaited = true;
3819
- return (resultPromise ||= promise()).then(onFulfilled, onRejected);
3820
- },
3821
- catch(onRejected) {
3822
- awaited = true;
3823
- return (resultPromise ||= promise()).catch(onRejected);
3824
- },
3825
- finally(onFinally) {
3826
- awaited = true;
3827
- return (resultPromise ||= promise()).finally(onFinally);
3828
- },
3829
- [Symbol.toStringTag]: "Promise"
3830
- };
3831
- };
3832
- } });
3833
- return proxy;
3834
- };
3835
- }
3836
- function copyStackTrace(target, source) {
3837
- if (source.stack !== void 0) target.stack = source.stack.replace(source.message, target.message);
3838
- return target;
3839
- }
3840
-
3841
- let _client;
3842
- function getSnapshotClient() {
3843
- if (!_client) _client = new SnapshotClient({ isEqual: (received, expected) => {
3844
- return equals(received, expected, [iterableEquality, subsetEquality]);
3845
- } });
3846
- return _client;
3847
- }
3848
- function getError(expected, promise) {
3849
- if (typeof expected !== "function") {
3850
- if (!promise) throw new Error(`expected must be a function, received ${typeof expected}`);
3851
- // when "promised", it receives thrown error
3852
- return expected;
3853
- }
3854
- try {
3855
- expected();
3856
- } catch (e) {
3857
- return e;
3858
- }
3859
- throw new Error("snapshot function didn't throw");
3860
- }
3861
- function getTestNames(test) {
3862
- return {
3863
- filepath: test.file.filepath,
3864
- name: getNames(test).slice(1).join(" > "),
3865
- testId: test.id
3866
- };
3867
- }
3868
- function getAssertionName(assertion) {
3869
- const name = chai.util.flag(assertion, "_name");
3870
- if (!name) throw new Error("Assertion name is not set. This is a bug in Vitest. Please, open a new issue with reproduction.");
3871
- return name;
3872
- }
3873
- function getTest(obj) {
3874
- const test = chai.util.flag(obj, "vitest-test");
3875
- if (!test) throw new Error(`'${getAssertionName(obj)}' cannot be used without test context`);
3876
- return test;
3877
- }
3878
- function validateAssertion(assertion) {
3879
- if (chai.util.flag(assertion, "negate")) throw new Error(`${getAssertionName(assertion)} cannot be used with "not"`);
3880
- }
3881
- const SnapshotPlugin = (chai, utils) => {
3882
- for (const key of ["matchSnapshot", "toMatchSnapshot"]) utils.addMethod(chai.Assertion.prototype, key, wrapAssertion(utils, key, function(propertiesOrHint, hint) {
3883
- return assertMatchResult(toMatchSnapshotImpl({
3884
- assertion: this,
3885
- received: utils.flag(this, "object"),
3886
- ...normalizeArguments(propertiesOrHint, hint)
3887
- }), chai.util.flag(this, "message"));
3888
- }));
3889
- utils.addMethod(chai.Assertion.prototype, "toMatchFileSnapshot", function(filepath, hint) {
3890
- // set name manually since it's not wrapped by wrapAssertion
3891
- utils.flag(this, "_name", "toMatchFileSnapshot");
3892
- // validate early synchronously just not to break some existing tests
3893
- validateAssertion(this);
3894
- const assertPromise = toMatchFileSnapshotImpl({
3895
- assertion: this,
3896
- received: utils.flag(this, "object"),
3897
- filepath,
3898
- hint
3899
- }).then((result) => assertMatchResult(result, chai.util.flag(this, "message")));
3900
- return recordAsyncExpect(getTest(this), assertPromise, createAssertionMessage(utils, this, true), /* @__PURE__ */ new Error("resolves"), utils.flag(this, "soft"));
3901
- });
3902
- utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", wrapAssertion(utils, "toMatchInlineSnapshot", function __INLINE_SNAPSHOT_OFFSET_3__(propertiesOrInlineSnapshot, inlineSnapshotOrHint, hint) {
3903
- return assertMatchResult(toMatchSnapshotImpl({
3904
- assertion: this,
3905
- received: utils.flag(this, "object"),
3906
- isInline: true,
3907
- ...normalizeInlineArguments(propertiesOrInlineSnapshot, inlineSnapshotOrHint, hint)
3908
- }), chai.util.flag(this, "message"));
3909
- }));
3910
- utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingSnapshot", wrapAssertion(utils, "toThrowErrorMatchingSnapshot", function(propertiesOrHint, hint) {
3911
- validateAssertion(this);
3912
- const received = utils.flag(this, "object");
3913
- const promise = utils.flag(this, "promise");
3914
- return assertMatchResult(toMatchSnapshotImpl({
3915
- assertion: this,
3916
- received: getError(received, promise),
3917
- ...normalizeArguments(propertiesOrHint, hint)
3918
- }), chai.util.flag(this, "message"));
3919
- }));
3920
- utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingInlineSnapshot", wrapAssertion(utils, "toThrowErrorMatchingInlineSnapshot", function __INLINE_SNAPSHOT_OFFSET_3__(inlineSnapshotOrHint, hint) {
3921
- validateAssertion(this);
3922
- const received = utils.flag(this, "object");
3923
- const promise = utils.flag(this, "promise");
3924
- return assertMatchResult(toMatchSnapshotImpl({
3925
- assertion: this,
3926
- received: getError(received, promise),
3927
- isInline: true,
3928
- ...normalizeInlineArguments(void 0, inlineSnapshotOrHint, hint)
3929
- }), chai.util.flag(this, "message"));
3930
- }));
3931
- utils.addMethod(chai.expect, "addSnapshotSerializer", addSerializer);
3932
- };
3933
- function toMatchDomainSnapshotImpl(opts) {
3934
- const { assertion } = opts;
3935
- validateAssertion(assertion);
3936
- const assertionName = getAssertionName(assertion);
3937
- const test = getTest(assertion);
3938
- let { inlineSnapshot } = opts;
3939
- if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
3940
- const pollFn = chai.util.flag(assertion, "_poll.fn");
3941
- if (pollFn) return getSnapshotClient().pollMatchDomain({
3942
- poll: pollFn,
3943
- adapter: opts.adapter,
3944
- message: opts.hint,
3945
- isInline: opts.isInline,
3946
- errorMessage: chai.util.flag(assertion, "message"),
3947
- timeout: chai.util.flag(assertion, "_poll.timeout"),
3948
- interval: chai.util.flag(assertion, "_poll.interval"),
3949
- assertionName,
3950
- inlineSnapshot,
3951
- error: chai.util.flag(assertion, "error"),
3952
- ...getTestNames(test)
3953
- });
3954
- return getSnapshotClient().matchDomain({
3955
- received: opts.received,
3956
- adapter: opts.adapter,
3957
- message: opts.hint,
3958
- isInline: opts.isInline,
3959
- errorMessage: chai.util.flag(assertion, "message"),
3960
- assertionName,
3961
- inlineSnapshot,
3962
- error: chai.util.flag(assertion, "error"),
3963
- ...getTestNames(test)
3964
- });
3965
- }
3966
- // toMatchSnapshot(propertiesOrHint?, hint?)
3967
- function normalizeArguments(propertiesOrHint, hint) {
3968
- if (typeof propertiesOrHint === "string") return { hint: propertiesOrHint };
3969
- return {
3970
- properties: propertiesOrHint,
3971
- hint
3972
- };
3973
- }
3974
- // toMatchInlineSnapshot(propertiesOrInlineSnapshot?, inlineSnapshotOrHint?, hint?)
3975
- function normalizeInlineArguments(propertiesOrInlineSnapshot, inlineSnapshotOrHint, hint) {
3976
- let inlineSnapshot;
3977
- if (typeof propertiesOrInlineSnapshot === "string") {
3978
- inlineSnapshot = stripSnapshotIndentation(propertiesOrInlineSnapshot);
3979
- return {
3980
- inlineSnapshot,
3981
- hint: inlineSnapshotOrHint
3982
- };
3983
- }
3984
- if (inlineSnapshotOrHint) inlineSnapshot = stripSnapshotIndentation(inlineSnapshotOrHint);
3985
- return {
3986
- properties: propertiesOrInlineSnapshot,
3987
- inlineSnapshot,
3988
- hint
3989
- };
3990
- }
3991
- function toMatchSnapshotImpl(options) {
3992
- const { assertion } = options;
3993
- validateAssertion(assertion);
3994
- const assertionName = getAssertionName(assertion);
3995
- const test = getTest(assertion);
3996
- return getSnapshotClient().match({
3997
- received: options.received,
3998
- properties: options.properties,
3999
- message: options.hint,
4000
- isInline: options.isInline,
4001
- inlineSnapshot: options.inlineSnapshot,
4002
- assertionName,
4003
- error: chai.util.flag(assertion, "error"),
4004
- ...getTestNames(test)
4005
- });
4006
- }
4007
- async function toMatchFileSnapshotImpl(options) {
4008
- const { assertion } = options;
4009
- validateAssertion(assertion);
4010
- const testNames = getTestNames(getTest(assertion));
4011
- const snapshotState = getSnapshotClient().getSnapshotState(testNames.filepath);
4012
- const rawSnapshotFile = await snapshotState.environment.resolveRawPath(testNames.filepath, options.filepath);
4013
- const rawSnapshotContent = await snapshotState.environment.readSnapshotFile(rawSnapshotFile);
4014
- return getSnapshotClient().match({
4015
- received: options.received,
4016
- message: options.hint,
4017
- rawSnapshot: {
4018
- file: rawSnapshotFile,
4019
- content: rawSnapshotContent ?? void 0
4020
- },
4021
- ...testNames
4022
- });
4023
- }
4024
- function assertMatchResult(result, customMessage) {
4025
- if (!result.pass) {
4026
- const errorMessage = (customMessage ? `${customMessage}: ` : "") + result.message();
4027
- throw Object.assign(new Error(errorMessage), {
4028
- actual: result.actual,
4029
- expected: result.expected,
4030
- diffOptions: { expand: getWorkerState().config.snapshotOptions.expand }
4031
- });
4032
- }
4033
- }
4034
- /**
4035
- * Composable snapshot matcher helpers for building custom snapshot matchers
4036
- * with `expect.extend`.
4037
- *
4038
- * @experimental
4039
- * @see https://vitest.dev/guide/snapshot.html#custom-snapshot-matchers
4040
- */
4041
- const Snapshots = {
4042
- toMatchSnapshot(received, propertiesOrHint, hint) {
4043
- return toMatchSnapshotImpl({
4044
- assertion: this.assertion,
4045
- received,
4046
- ...normalizeArguments(propertiesOrHint, hint)
4047
- });
4048
- },
4049
- toMatchInlineSnapshot(received, propertiesOrInlineSnapshot, inlineSnapshotOrHint, hint) {
4050
- return toMatchSnapshotImpl({
4051
- assertion: this.assertion,
4052
- received,
4053
- isInline: true,
4054
- ...normalizeInlineArguments(propertiesOrInlineSnapshot, inlineSnapshotOrHint, hint)
4055
- });
4056
- },
4057
- toMatchFileSnapshot(received, filepath, hint) {
4058
- return toMatchFileSnapshotImpl({
4059
- assertion: this.assertion,
4060
- received,
4061
- filepath,
4062
- hint
4063
- });
4064
- },
4065
- toMatchDomainSnapshot(domain, received) {
4066
- return toMatchDomainSnapshotImpl({
4067
- assertion: this.assertion,
4068
- adapter: domain,
4069
- received
4070
- });
4071
- },
4072
- toMatchDomainInlineSnapshot(domain, received, inlineSnapshot) {
4073
- return toMatchDomainSnapshotImpl({
4074
- assertion: this.assertion,
4075
- adapter: domain,
4076
- received,
4077
- isInline: true,
4078
- inlineSnapshot
4079
- });
4080
- }
4081
- };
4082
-
4083
- chai.use(JestExtend);
4084
- chai.use(JestChaiExpect);
4085
- chai.use(ChaiStyleAssertions);
4086
- chai.use(SnapshotPlugin);
4087
- chai.use(JestAsymmetricMatchers);
4088
-
4089
- function createExpect(test) {
4090
- const expect = ((value, message) => {
4091
- const { assertionCalls } = getState(expect);
4092
- setState({ assertionCalls: assertionCalls + 1 }, expect);
4093
- const assert = chai.expect(value, message);
4094
- const _test = test || getCurrentTest();
4095
- if (_test)
4096
- // @ts-expect-error internal
4097
- return assert.withTest(_test);
4098
- else return assert;
4099
- });
4100
- Object.assign(expect, chai.expect);
4101
- Object.assign(expect, globalThis[ASYMMETRIC_MATCHERS_OBJECT]);
4102
- expect.getState = () => getState(expect);
4103
- expect.setState = (state) => setState(state, expect);
4104
- // @ts-expect-error global is not typed
4105
- const globalState = getState(globalThis[GLOBAL_EXPECT]) || {};
4106
- setState({
4107
- ...globalState,
4108
- assertionCalls: 0,
4109
- isExpectingAssertions: false,
4110
- isExpectingAssertionsError: null,
4111
- expectedAssertionsNumber: null,
4112
- expectedAssertionsNumberErrorGen: null,
4113
- get testPath() {
4114
- return getWorkerState().filepath;
4115
- },
4116
- currentTestName: test ? test.fullTestName ?? "" : globalState.currentTestName
4117
- }, expect);
4118
- expect.assert = chai.assert;
4119
- // @ts-expect-error untyped
4120
- expect.extend = (matchers) => chai.expect.extend(expect, matchers);
4121
- expect.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters);
4122
- expect.soft = (...args) => {
4123
- // @ts-expect-error private soft access
4124
- return expect(...args).withContext({ soft: true });
4125
- };
4126
- expect.poll = createExpectPoll(expect);
4127
- expect.unreachable = (message) => {
4128
- chai.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
4129
- };
4130
- function assertions(expected) {
4131
- const errorGen = () => /* @__PURE__ */ new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
4132
- if (Error.captureStackTrace) Error.captureStackTrace(errorGen(), assertions);
4133
- expect.setState({
4134
- expectedAssertionsNumber: expected,
4135
- expectedAssertionsNumberErrorGen: errorGen
4136
- });
4137
- }
4138
- function hasAssertions() {
4139
- const error = /* @__PURE__ */ new Error("expected any number of assertion, but got none");
4140
- if (Error.captureStackTrace) Error.captureStackTrace(error, hasAssertions);
4141
- expect.setState({
4142
- isExpectingAssertions: true,
4143
- isExpectingAssertionsError: error
4144
- });
4145
- }
4146
- chai.util.addMethod(expect, "assertions", assertions);
4147
- chai.util.addMethod(expect, "hasAssertions", hasAssertions);
4148
- expect.extend(customMatchers);
4149
- return expect;
4150
- }
4151
- const globalExpect = createExpect();
4152
- Object.defineProperty(globalThis, GLOBAL_EXPECT, {
4153
- value: globalExpect,
4154
- writable: true,
4155
- configurable: true
4156
- });
4157
- const assert = chai.assert;
4158
- const should = chai.should;
4159
-
4160
- /**
4161
- * Gives access to injected context provided from the main thread.
4162
- * This usually returns a value provided by `globalSetup` or an external library.
4163
- */
4164
- function inject(key) {
4165
- return getWorkerState().providedContext[key];
4166
- }
4167
-
4168
- function createBenchmarkResult(name) {
4169
- return {
4170
- name,
4171
- rank: 0,
4172
- rme: 0,
4173
- samples: []
4174
- };
4175
- }
4176
- const benchmarkTasks = /* @__PURE__ */ new WeakMap();
4177
- async function runBenchmarkSuite(suite, runner) {
4178
- const { Task, Bench } = await runner.importTinybench();
4179
- const start = performance.now();
4180
- const benchmarkGroup = [];
4181
- const benchmarkSuiteGroup = [];
4182
- for (const task of suite.tasks) {
4183
- if (task.mode !== "run" && task.mode !== "queued") continue;
4184
- if (task.meta?.benchmark) benchmarkGroup.push(task);
4185
- else if (task.type === "suite") benchmarkSuiteGroup.push(task);
4186
- }
4187
- // run sub suites sequentially
4188
- for (const subSuite of benchmarkSuiteGroup) await runBenchmarkSuite(subSuite, runner);
4189
- if (benchmarkGroup.length) {
4190
- const defer = createDefer();
4191
- suite.result = {
4192
- state: "run",
4193
- startTime: start,
4194
- benchmark: createBenchmarkResult(suite.name)
4195
- };
4196
- updateTask$1("suite-prepare", suite);
4197
- const addBenchTaskListener = (task, benchmark) => {
4198
- task.addEventListener("complete", (e) => {
4199
- const taskRes = e.task.result;
4200
- const result = benchmark.result.benchmark;
4201
- benchmark.result.state = "pass";
4202
- Object.assign(result, taskRes);
4203
- // compute extra stats and free raw samples as early as possible
4204
- const samples = result.samples;
4205
- result.sampleCount = samples.length;
4206
- result.median = samples.length % 2 ? samples[Math.floor(samples.length / 2)] : (samples[samples.length / 2] + samples[samples.length / 2 - 1]) / 2;
4207
- if (!runner.config.benchmark?.includeSamples) result.samples.length = 0;
4208
- updateTask$1("test-finished", benchmark);
4209
- }, { once: true });
4210
- task.addEventListener("error", (e) => {
4211
- const task = e.task;
4212
- defer.reject(benchmark ? task.result.error : e);
4213
- }, { once: true });
4214
- };
4215
- benchmarkGroup.forEach((benchmark) => {
4216
- const benchmarkInstance = new Bench(getBenchOptions(benchmark));
4217
- const benchmarkFn = getBenchFn(benchmark);
4218
- benchmark.result = {
4219
- state: "run",
4220
- startTime: start,
4221
- benchmark: createBenchmarkResult(benchmark.name)
4222
- };
4223
- const task = new Task(benchmarkInstance, benchmark.name, benchmarkFn);
4224
- benchmarkTasks.set(benchmark, task);
4225
- addBenchTaskListener(task, benchmark);
4226
- });
4227
- const { setTimeout } = getSafeTimers();
4228
- const tasks = [];
4229
- for (const benchmark of benchmarkGroup) {
4230
- const task = benchmarkTasks.get(benchmark);
4231
- updateTask$1("test-prepare", benchmark);
4232
- await task.warmup();
4233
- tasks.push([await new Promise((resolve) => setTimeout(async () => {
4234
- resolve(await task.run());
4235
- })), benchmark]);
4236
- }
4237
- suite.result.duration = performance.now() - start;
4238
- suite.result.state = "pass";
4239
- updateTask$1("suite-finished", suite);
4240
- defer.resolve(null);
4241
- await defer;
4242
- }
4243
- function updateTask$1(event, task) {
4244
- updateTask(event, task, runner);
4245
- }
4246
- }
4247
- class NodeBenchmarkRunner {
4248
- moduleRunner;
4249
- constructor(config) {
4250
- this.config = config;
4251
- }
4252
- async importTinybench() {
4253
- return await import('tinybench');
4254
- }
4255
- importFile(filepath, source) {
4256
- if (source === "setup") {
4257
- const moduleNode = getWorkerState().evaluatedModules.getModuleById(filepath);
4258
- if (moduleNode) getWorkerState().evaluatedModules.invalidateModule(moduleNode);
4259
- }
4260
- return this.moduleRunner.import(filepath);
4261
- }
4262
- async runSuite(suite) {
4263
- await runBenchmarkSuite(suite, this);
4264
- }
4265
- async runTask() {
4266
- throw new Error("`test()` and `it()` is only available in test mode.");
4267
- }
4268
- }
4269
-
4270
- class TestRunner {
4271
- snapshotClient = getSnapshotClient();
4272
- workerState = getWorkerState();
4273
- moduleRunner;
4274
- cancelRun = false;
4275
- assertionsErrors = /* @__PURE__ */ new WeakMap();
4276
- pool = this.workerState.ctx.pool;
4277
- _otel;
4278
- viteEnvironment;
4279
- viteModuleRunner;
4280
- constructor(config) {
4281
- this.config = config;
4282
- const environment = this.workerState.environment;
4283
- this.viteEnvironment = environment.viteEnvironment || environment.name;
4284
- this.viteModuleRunner = config.experimental.viteModuleRunner;
4285
- }
4286
- importFile(filepath, source) {
4287
- if (source === "setup") {
4288
- const moduleNode = this.workerState.evaluatedModules.getModuleById(filepath);
4289
- if (moduleNode) this.workerState.evaluatedModules.invalidateModule(moduleNode);
4290
- }
4291
- return this._otel.$(`vitest.module.import_${source === "setup" ? "setup" : "spec"}`, { attributes: { "code.file.path": filepath } }, () => {
4292
- if (!this.viteModuleRunner) filepath = `${filepath}?vitest=${Date.now()}`;
4293
- return this.moduleRunner.import(filepath);
4294
- });
4295
- }
4296
- onCollectStart(file) {
4297
- this.workerState.current = file;
4298
- }
4299
- onCleanupWorkerContext(listener) {
4300
- this.workerState.onCleanup(listener);
4301
- }
4302
- onAfterRunFiles() {
4303
- this.snapshotClient.clear();
4304
- this.workerState.current = void 0;
4305
- }
4306
- async onAfterRunSuite(suite) {
4307
- if (this.config.logHeapUsage && typeof process !== "undefined") suite.result.heap = process.memoryUsage().heapUsed;
4308
- if (suite.mode !== "skip" && "filepath" in suite) {
4309
- // mark snapshots in skipped tests as not obsolete
4310
- for (const test of getTests(suite)) if (test.mode === "skip") {
4311
- const name = getNames(test).slice(1).join(" > ");
4312
- this.snapshotClient.skipTest(suite.file.filepath, name);
4313
- }
4314
- const result = await this.snapshotClient.finish(suite.file.filepath);
4315
- if (this.workerState.config.snapshotOptions.updateSnapshot === "none" && result.unchecked) {
4316
- let message = `Obsolete snapshots found when no snapshot update is expected.\n`;
4317
- for (const key of result.uncheckedKeys) message += `· ${key}\n`;
4318
- suite.result.errors ??= [];
4319
- suite.result.errors.push(processError(new Error(message)));
4320
- suite.result.state = "fail";
4321
- }
4322
- await rpc().snapshotSaved(result);
4323
- }
4324
- this.workerState.current = suite.suite || suite.file;
4325
- }
4326
- onAfterRunTask(test) {
4327
- if (this.config.logHeapUsage && typeof process !== "undefined") test.result.heap = process.memoryUsage().heapUsed;
4328
- this.workerState.current = test.suite || test.file;
4329
- }
4330
- cancel(_reason) {
4331
- this.cancelRun = true;
4332
- }
4333
- injectValue(key) {
4334
- // inject has a very limiting type controlled by ProvidedContext
4335
- // some tests override it which causes the build to fail
4336
- return inject(key);
4337
- }
4338
- async onBeforeRunTask(test) {
4339
- if (this.cancelRun) test.mode = "skip";
4340
- if (test.mode !== "run" && test.mode !== "queued") return;
4341
- this.workerState.current = test;
4342
- }
4343
- async onBeforeRunSuite(suite) {
4344
- if (this.cancelRun) suite.mode = "skip";
4345
- // initialize snapshot state before running file suite
4346
- if (suite.mode !== "skip" && "filepath" in suite) await this.snapshotClient.setup(suite.file.filepath, this.workerState.config.snapshotOptions);
4347
- this.workerState.current = suite;
4348
- }
4349
- onBeforeTryTask(test) {
4350
- clearModuleMocks(this.config);
4351
- this.snapshotClient.clearTest(test.file.filepath, test.id);
4352
- setState({
4353
- assertionCalls: 0,
4354
- isExpectingAssertions: false,
4355
- isExpectingAssertionsError: null,
4356
- expectedAssertionsNumber: null,
4357
- expectedAssertionsNumberErrorGen: null,
4358
- currentTestName: getTestName(test),
4359
- snapshotState: this.snapshotClient.getSnapshotState(test.file.filepath)
4360
- }, globalThis[GLOBAL_EXPECT]);
4361
- }
4362
- onAfterTryTask(test) {
4363
- const { assertionCalls, expectedAssertionsNumber, expectedAssertionsNumberErrorGen, isExpectingAssertions, isExpectingAssertionsError } = test.context._local ? test.context.expect.getState() : getState(globalThis[GLOBAL_EXPECT]);
4364
- if (expectedAssertionsNumber !== null && assertionCalls !== expectedAssertionsNumber) throw expectedAssertionsNumberErrorGen();
4365
- if (isExpectingAssertions === true && assertionCalls === 0) throw isExpectingAssertionsError;
4366
- if (this.config.expect.requireAssertions && assertionCalls === 0) throw this.assertionsErrors.get(test);
4367
- }
4368
- extendTaskContext(context) {
4369
- // create error during the test initialization so we have a nice stack trace
4370
- if (this.config.expect.requireAssertions) this.assertionsErrors.set(context.task, /* @__PURE__ */ new Error("expected any number of assertion, but got none"));
4371
- let _expect;
4372
- Object.defineProperty(context, "expect", { get() {
4373
- if (!_expect) _expect = createExpect(context.task);
4374
- return _expect;
4375
- } });
4376
- Object.defineProperty(context, "_local", { get() {
4377
- return _expect != null;
4378
- } });
4379
- return context;
4380
- }
4381
- getImportDurations() {
4382
- const { limit } = this.config.experimental.importDurations;
4383
- // skip sorting if limit is 0
4384
- if (limit === 0) return {};
4385
- // Sort by duration descending and keep top entries
4386
- const sortedEntries = [...this.workerState.moduleExecutionInfo?.entries() || []].sort(([, a], [, b]) => b.duration - a.duration).slice(0, limit);
4387
- const importDurations = {};
4388
- for (const [filepath, { duration, selfTime, external, importer }] of sortedEntries) importDurations[normalize(filepath)] = {
4389
- selfTime,
4390
- totalTime: duration,
4391
- external,
4392
- importer
4393
- };
4394
- return importDurations;
4395
- }
4396
- trace = (name, attributes, cb) => {
4397
- const options = typeof attributes === "object" ? { attributes } : {};
4398
- return this._otel.$(`vitest.test.runner.${name}`, options, cb || attributes);
4399
- };
4400
- __setTraces(traces) {
4401
- this._otel = traces;
4402
- }
4403
- static createTaskCollector = createTaskCollector;
4404
- static getCurrentSuite = getCurrentSuite;
4405
- static getCurrentTest = getCurrentTest;
4406
- static createChainable = createChainable;
4407
- static getSuiteHooks = getHooks;
4408
- static getTestFn = getFn;
4409
- static setSuiteHooks = getHooks;
4410
- static setTestFn = getFn;
4411
- static matchesTags = matchesTags;
4412
- /**
4413
- * @deprecated
4414
- */
4415
- static getBenchFn = getBenchFn;
4416
- /**
4417
- * @deprecated
4418
- */
4419
- static getBenchOptions = getBenchOptions;
4420
- }
4421
- function clearModuleMocks(config) {
4422
- const { clearMocks, mockReset, restoreMocks, unstubEnvs, unstubGlobals } = config;
4423
- if (restoreMocks) vi.restoreAllMocks();
4424
- if (mockReset) vi.resetAllMocks();
4425
- if (clearMocks) vi.clearAllMocks();
4426
- if (unstubEnvs) vi.unstubAllEnvs();
4427
- if (unstubGlobals) vi.unstubAllGlobals();
4428
- }
4429
-
4430
- export { NodeBenchmarkRunner as N, Snapshots as S, TestRunner as T, assert as a, vitest as b, createExpect as c, globalExpect as g, inject as i, should as s, vi as v };