vitest 1.0.0-beta.0 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/dist/browser.d.ts +2 -2
  3. package/dist/browser.js +2 -2
  4. package/dist/child.js +1 -1
  5. package/dist/{chunk-api-setup.0aeabd21.js → chunk-api-setup.5d9a93c7.js} +3 -0
  6. package/dist/{chunk-install-pkg.991b9ea3.js → chunk-install-pkg.43d58972.js} +17 -14
  7. package/dist/{chunk-integrations-globals.c3c5e678.js → chunk-integrations-globals.9df12d91.js} +2 -3
  8. package/dist/{chunk-node-git.36288174.js → chunk-node-git.2f1df48f.js} +1 -1
  9. package/dist/{chunk-runtime-console.ea222ffb.js → chunk-runtime-console.f3263f87.js} +19 -4
  10. package/dist/cli-wrapper.js +1 -1
  11. package/dist/cli.js +7 -4
  12. package/dist/config.cjs +2 -1
  13. package/dist/config.d.ts +2 -2
  14. package/dist/config.js +2 -1
  15. package/dist/coverage.d.ts +1 -1
  16. package/dist/entry-vm.js +8 -3
  17. package/dist/entry.js +9 -4
  18. package/dist/environments.d.ts +1 -1
  19. package/dist/environments.js +1 -1
  20. package/dist/execute.d.ts +1 -1
  21. package/dist/index.d.ts +5 -4
  22. package/dist/index.js +3 -4
  23. package/dist/node.d.ts +2 -2
  24. package/dist/node.js +8 -5
  25. package/dist/{reporters-7bd09217.d.ts → reporters-d10f25e1.d.ts} +23 -18
  26. package/dist/reporters.d.ts +1 -1
  27. package/dist/reporters.js +6 -1
  28. package/dist/runners.d.ts +1 -1
  29. package/dist/runners.js +1 -2
  30. package/dist/{suite-543d56bd.d.ts → suite-919dd548.d.ts} +1 -1
  31. package/dist/suite.d.ts +2 -2
  32. package/dist/{vendor-environments.e73c5410.js → vendor-environments.094f240c.js} +2 -0
  33. package/dist/{vendor-index.f7fcd5e8.js → vendor-index.68ecee35.js} +1 -1
  34. package/dist/{vendor-index.85fc950a.js → vendor-index.e006069f.js} +4 -4
  35. package/dist/{vendor-node.6fe91553.js → vendor-node.e5a35bfe.js} +83 -46
  36. package/dist/{vendor-reporters.f6975b8d.js → vendor-reporters.2953082e.js} +2 -1
  37. package/dist/vendor-vi.d30b47ae.js +3510 -0
  38. package/dist/vm.js +2 -2
  39. package/dist/worker.js +1 -1
  40. package/package.json +10 -10
  41. package/dist/vendor-vi.7f2b988f.js +0 -3491
@@ -1,3491 +0,0 @@
1
- import * as chai$1 from 'chai';
2
- import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './vendor-_commonjsHelpers.7d1333e8.js';
3
- import { equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, JestAsymmetricMatchers, GLOBAL_EXPECT as GLOBAL_EXPECT$1, getState, setState } from '@vitest/expect';
4
- import { stripSnapshotIndentation, addSerializer, SnapshotClient } from '@vitest/snapshot';
5
- import { getNames } from '@vitest/runner/utils';
6
- import '@vitest/utils/error';
7
- import { getCurrentTest } from '@vitest/runner';
8
- import { g as getFullName } from './vendor-tasks.f9d75aed.js';
9
- import { g as getWorkerState, a as getCurrentEnvironment } from './vendor-global.97e4527c.js';
10
- import { getSafeTimers, assertTypes, createSimpleStackTrace } from '@vitest/utils';
11
- import { parseSingleStack } from '@vitest/utils/source-map';
12
- import require$$2 from 'util';
13
- import { R as RealDate, r as resetDate, m as mockDate } from './vendor-date.6e993429.js';
14
- import { spyOn, fn, isMockFunction, spies } from '@vitest/spy';
15
-
16
- function resetModules(modules, resetMocks = false) {
17
- const skipPaths = [
18
- // Vitest
19
- /\/vitest\/dist\//,
20
- /\/vite-node\/dist\//,
21
- // yarn's .store folder
22
- /vitest-virtual-\w+\/dist/,
23
- // cnpm
24
- /@vitest\/dist/,
25
- // don't clear mocks
26
- ...!resetMocks ? [/^mock:/] : []
27
- ];
28
- modules.forEach((mod, path) => {
29
- if (skipPaths.some((re) => re.test(path)))
30
- return;
31
- modules.invalidateModule(mod);
32
- });
33
- }
34
- function waitNextTick() {
35
- const { setTimeout } = getSafeTimers();
36
- return new Promise((resolve) => setTimeout(resolve, 0));
37
- }
38
- async function waitForImportsToResolve() {
39
- await waitNextTick();
40
- const state = getWorkerState();
41
- const promises = [];
42
- let resolvingCount = 0;
43
- for (const mod of state.moduleCache.values()) {
44
- if (mod.promise && !mod.evaluated)
45
- promises.push(mod.promise);
46
- if (mod.resolving)
47
- resolvingCount++;
48
- }
49
- if (!promises.length && !resolvingCount)
50
- return;
51
- await Promise.allSettled(promises);
52
- await waitForImportsToResolve();
53
- }
54
-
55
- function commonjsRequire(path) {
56
- throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
57
- }
58
-
59
- var chaiSubset = {exports: {}};
60
-
61
- (function (module, exports) {
62
- (function() {
63
- (function(chaiSubset) {
64
- if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
65
- return module.exports = chaiSubset;
66
- } else {
67
- return chai.use(chaiSubset);
68
- }
69
- })(function(chai, utils) {
70
- var Assertion = chai.Assertion;
71
- var assertionPrototype = Assertion.prototype;
72
-
73
- Assertion.addMethod('containSubset', function (expected) {
74
- var actual = utils.flag(this, 'object');
75
- var showDiff = chai.config.showDiff;
76
-
77
- assertionPrototype.assert.call(this,
78
- compare(expected, actual),
79
- 'expected #{act} to contain subset #{exp}',
80
- 'expected #{act} to not contain subset #{exp}',
81
- expected,
82
- actual,
83
- showDiff
84
- );
85
- });
86
-
87
- chai.assert.containSubset = function(val, exp, msg) {
88
- new chai.Assertion(val, msg).to.be.containSubset(exp);
89
- };
90
-
91
- function compare(expected, actual) {
92
- if (expected === actual) {
93
- return true;
94
- }
95
- if (typeof(actual) !== typeof(expected)) {
96
- return false;
97
- }
98
- if (typeof(expected) !== 'object' || expected === null) {
99
- return expected === actual;
100
- }
101
- if (!!expected && !actual) {
102
- return false;
103
- }
104
-
105
- if (Array.isArray(expected)) {
106
- if (typeof(actual.length) !== 'number') {
107
- return false;
108
- }
109
- var aa = Array.prototype.slice.call(actual);
110
- return expected.every(function (exp) {
111
- return aa.some(function (act) {
112
- return compare(exp, act);
113
- });
114
- });
115
- }
116
-
117
- if (expected instanceof Date) {
118
- if (actual instanceof Date) {
119
- return expected.getTime() === actual.getTime();
120
- } else {
121
- return false;
122
- }
123
- }
124
-
125
- return Object.keys(expected).every(function (key) {
126
- var eo = expected[key];
127
- var ao = actual[key];
128
- if (typeof(eo) === 'object' && eo !== null && ao !== null) {
129
- return compare(eo, ao);
130
- }
131
- if (typeof(eo) === 'function') {
132
- return eo(ao);
133
- }
134
- return ao === eo;
135
- });
136
- }
137
- });
138
-
139
- }).call(commonjsGlobal);
140
- } (chaiSubset));
141
-
142
- var chaiSubsetExports = chaiSubset.exports;
143
- var Subset = /*@__PURE__*/getDefaultExportFromCjs(chaiSubsetExports);
144
-
145
- const MATCHERS_OBJECT = Symbol.for("matchers-object");
146
- const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object");
147
- const GLOBAL_EXPECT = Symbol.for("expect-global");
148
-
149
- if (!Object.prototype.hasOwnProperty.call(globalThis, MATCHERS_OBJECT)) {
150
- const globalState = /* @__PURE__ */ new WeakMap();
151
- const matchers = /* @__PURE__ */ Object.create(null);
152
- Object.defineProperty(globalThis, MATCHERS_OBJECT, {
153
- get: () => globalState
154
- });
155
- Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, {
156
- configurable: true,
157
- get: () => ({
158
- state: globalState.get(globalThis[GLOBAL_EXPECT]),
159
- matchers
160
- })
161
- });
162
- }
163
-
164
- function recordAsyncExpect(test, promise) {
165
- if (test && promise instanceof Promise) {
166
- promise = promise.finally(() => {
167
- const index = test.promises.indexOf(promise);
168
- if (index !== -1)
169
- test.promises.splice(index, 1);
170
- });
171
- if (!test.promises)
172
- test.promises = [];
173
- test.promises.push(promise);
174
- }
175
- return promise;
176
- }
177
-
178
- let _client;
179
- function getSnapshotClient() {
180
- if (!_client) {
181
- _client = new SnapshotClient({
182
- isEqual: (received, expected) => {
183
- return equals(received, expected, [iterableEquality, subsetEquality]);
184
- }
185
- });
186
- }
187
- return _client;
188
- }
189
- function getErrorMessage(err) {
190
- if (err instanceof Error)
191
- return err.message;
192
- return err;
193
- }
194
- function getErrorString(expected, promise) {
195
- if (typeof expected !== "function") {
196
- if (!promise)
197
- throw new Error(`expected must be a function, received ${typeof expected}`);
198
- return getErrorMessage(expected);
199
- }
200
- try {
201
- expected();
202
- } catch (e) {
203
- return getErrorMessage(e);
204
- }
205
- throw new Error("snapshot function didn't throw");
206
- }
207
- const SnapshotPlugin = (chai, utils) => {
208
- const getTestNames = (test) => {
209
- var _a;
210
- if (!test)
211
- return {};
212
- return {
213
- filepath: (_a = test.file) == null ? void 0 : _a.filepath,
214
- name: getNames(test).slice(1).join(" > ")
215
- };
216
- };
217
- for (const key of ["matchSnapshot", "toMatchSnapshot"]) {
218
- utils.addMethod(
219
- chai.Assertion.prototype,
220
- key,
221
- function(properties, message) {
222
- const expected = utils.flag(this, "object");
223
- const test = utils.flag(this, "vitest-test");
224
- if (typeof properties === "string" && typeof message === "undefined") {
225
- message = properties;
226
- properties = void 0;
227
- }
228
- const errorMessage = utils.flag(this, "message");
229
- getSnapshotClient().assert({
230
- received: expected,
231
- message,
232
- isInline: false,
233
- properties,
234
- errorMessage,
235
- ...getTestNames(test)
236
- });
237
- }
238
- );
239
- }
240
- utils.addMethod(
241
- chai.Assertion.prototype,
242
- "toMatchFileSnapshot",
243
- function(file, message) {
244
- const expected = utils.flag(this, "object");
245
- const test = utils.flag(this, "vitest-test");
246
- const errorMessage = utils.flag(this, "message");
247
- const promise = getSnapshotClient().assertRaw({
248
- received: expected,
249
- message,
250
- isInline: false,
251
- rawSnapshot: {
252
- file
253
- },
254
- errorMessage,
255
- ...getTestNames(test)
256
- });
257
- return recordAsyncExpect(test, promise);
258
- }
259
- );
260
- utils.addMethod(
261
- chai.Assertion.prototype,
262
- "toMatchInlineSnapshot",
263
- function __INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
264
- var _a;
265
- const test = utils.flag(this, "vitest-test");
266
- const isInsideEach = test && (test.each || ((_a = test.suite) == null ? void 0 : _a.each));
267
- if (isInsideEach)
268
- throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
269
- const expected = utils.flag(this, "object");
270
- const error = utils.flag(this, "error");
271
- if (typeof properties === "string") {
272
- message = inlineSnapshot;
273
- inlineSnapshot = properties;
274
- properties = void 0;
275
- }
276
- if (inlineSnapshot)
277
- inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
278
- const errorMessage = utils.flag(this, "message");
279
- getSnapshotClient().assert({
280
- received: expected,
281
- message,
282
- isInline: true,
283
- properties,
284
- inlineSnapshot,
285
- error,
286
- errorMessage,
287
- ...getTestNames(test)
288
- });
289
- }
290
- );
291
- utils.addMethod(
292
- chai.Assertion.prototype,
293
- "toThrowErrorMatchingSnapshot",
294
- function(message) {
295
- const expected = utils.flag(this, "object");
296
- const test = utils.flag(this, "vitest-test");
297
- const promise = utils.flag(this, "promise");
298
- const errorMessage = utils.flag(this, "message");
299
- getSnapshotClient().assert({
300
- received: getErrorString(expected, promise),
301
- message,
302
- errorMessage,
303
- ...getTestNames(test)
304
- });
305
- }
306
- );
307
- utils.addMethod(
308
- chai.Assertion.prototype,
309
- "toThrowErrorMatchingInlineSnapshot",
310
- function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
311
- var _a;
312
- const test = utils.flag(this, "vitest-test");
313
- const isInsideEach = test && (test.each || ((_a = test.suite) == null ? void 0 : _a.each));
314
- if (isInsideEach)
315
- throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
316
- const expected = utils.flag(this, "object");
317
- const error = utils.flag(this, "error");
318
- const promise = utils.flag(this, "promise");
319
- const errorMessage = utils.flag(this, "message");
320
- getSnapshotClient().assert({
321
- received: getErrorString(expected, promise),
322
- message,
323
- inlineSnapshot,
324
- isInline: true,
325
- error,
326
- errorMessage,
327
- ...getTestNames(test)
328
- });
329
- }
330
- );
331
- utils.addMethod(
332
- chai.expect,
333
- "addSnapshotSerializer",
334
- addSerializer
335
- );
336
- };
337
-
338
- chai$1.use(JestExtend);
339
- chai$1.use(JestChaiExpect);
340
- chai$1.use(Subset);
341
- chai$1.use(SnapshotPlugin);
342
- chai$1.use(JestAsymmetricMatchers);
343
-
344
- function createExpect(test) {
345
- var _a;
346
- const expect = (value, message) => {
347
- const { assertionCalls } = getState(expect);
348
- setState({ assertionCalls: assertionCalls + 1, soft: false }, expect);
349
- const assert2 = chai$1.expect(value, message);
350
- const _test = test || getCurrentTest();
351
- if (_test)
352
- return assert2.withTest(_test);
353
- else
354
- return assert2;
355
- };
356
- Object.assign(expect, chai$1.expect);
357
- expect.getState = () => getState(expect);
358
- expect.setState = (state) => setState(state, expect);
359
- const globalState = getState(globalThis[GLOBAL_EXPECT$1]) || {};
360
- setState({
361
- // this should also add "snapshotState" that is added conditionally
362
- ...globalState,
363
- assertionCalls: 0,
364
- isExpectingAssertions: false,
365
- isExpectingAssertionsError: null,
366
- expectedAssertionsNumber: null,
367
- expectedAssertionsNumberErrorGen: null,
368
- environment: getCurrentEnvironment(),
369
- testPath: test ? (_a = test.suite.file) == null ? void 0 : _a.filepath : globalState.testPath,
370
- currentTestName: test ? getFullName(test) : globalState.currentTestName
371
- }, expect);
372
- expect.extend = (matchers) => chai$1.expect.extend(expect, matchers);
373
- expect.soft = (...args) => {
374
- const assert2 = expect(...args);
375
- expect.setState({
376
- soft: true
377
- });
378
- return assert2;
379
- };
380
- expect.unreachable = (message) => {
381
- chai$1.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
382
- };
383
- function assertions(expected) {
384
- const errorGen = () => new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
385
- if (Error.captureStackTrace)
386
- Error.captureStackTrace(errorGen(), assertions);
387
- expect.setState({
388
- expectedAssertionsNumber: expected,
389
- expectedAssertionsNumberErrorGen: errorGen
390
- });
391
- }
392
- function hasAssertions() {
393
- const error = new Error("expected any number of assertion, but got none");
394
- if (Error.captureStackTrace)
395
- Error.captureStackTrace(error, hasAssertions);
396
- expect.setState({
397
- isExpectingAssertions: true,
398
- isExpectingAssertionsError: error
399
- });
400
- }
401
- chai$1.util.addMethod(expect, "assertions", assertions);
402
- chai$1.util.addMethod(expect, "hasAssertions", hasAssertions);
403
- return expect;
404
- }
405
- const globalExpect = createExpect();
406
- Object.defineProperty(globalThis, GLOBAL_EXPECT$1, {
407
- value: globalExpect,
408
- writable: true,
409
- configurable: true
410
- });
411
-
412
- var fakeTimersSrc = {exports: {}};
413
-
414
- /**
415
- * A reference to the global object
416
- *
417
- * @type {object} globalObject
418
- */
419
- var globalObject;
420
-
421
- /* istanbul ignore else */
422
- if (typeof commonjsGlobal !== "undefined") {
423
- // Node
424
- globalObject = commonjsGlobal;
425
- } else if (typeof window !== "undefined") {
426
- // Browser
427
- globalObject = window;
428
- } else {
429
- // WebWorker
430
- globalObject = self;
431
- }
432
-
433
- var global = globalObject;
434
-
435
- /**
436
- * Is true when the environment causes an error to be thrown for accessing the
437
- * __proto__ property.
438
- *
439
- * This is necessary in order to support `node --disable-proto=throw`.
440
- *
441
- * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
442
- *
443
- * @type {boolean}
444
- */
445
- let throwsOnProto$1;
446
- try {
447
- const object = {};
448
- // eslint-disable-next-line no-proto, no-unused-expressions
449
- object.__proto__;
450
- throwsOnProto$1 = false;
451
- } catch (_) {
452
- // This branch is covered when tests are run with `--disable-proto=throw`,
453
- // however we can test both branches at the same time, so this is ignored
454
- /* istanbul ignore next */
455
- throwsOnProto$1 = true;
456
- }
457
-
458
- var throwsOnProto_1 = throwsOnProto$1;
459
-
460
- var call = Function.call;
461
- var throwsOnProto = throwsOnProto_1;
462
-
463
- var disallowedProperties = [
464
- // ignore size because it throws from Map
465
- "size",
466
- "caller",
467
- "callee",
468
- "arguments",
469
- ];
470
-
471
- // This branch is covered when tests are run with `--disable-proto=throw`,
472
- // however we can test both branches at the same time, so this is ignored
473
- /* istanbul ignore next */
474
- if (throwsOnProto) {
475
- disallowedProperties.push("__proto__");
476
- }
477
-
478
- var copyPrototypeMethods = function copyPrototypeMethods(prototype) {
479
- // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
480
- return Object.getOwnPropertyNames(prototype).reduce(function (
481
- result,
482
- name
483
- ) {
484
- if (disallowedProperties.includes(name)) {
485
- return result;
486
- }
487
-
488
- if (typeof prototype[name] !== "function") {
489
- return result;
490
- }
491
-
492
- result[name] = call.bind(prototype[name]);
493
-
494
- return result;
495
- },
496
- Object.create(null));
497
- };
498
-
499
- var copyPrototype$5 = copyPrototypeMethods;
500
-
501
- var array = copyPrototype$5(Array.prototype);
502
-
503
- var every$1 = array.every;
504
-
505
- /**
506
- * @private
507
- */
508
- function hasCallsLeft(callMap, spy) {
509
- if (callMap[spy.id] === undefined) {
510
- callMap[spy.id] = 0;
511
- }
512
-
513
- return callMap[spy.id] < spy.callCount;
514
- }
515
-
516
- /**
517
- * @private
518
- */
519
- function checkAdjacentCalls(callMap, spy, index, spies) {
520
- var calledBeforeNext = true;
521
-
522
- if (index !== spies.length - 1) {
523
- calledBeforeNext = spy.calledBefore(spies[index + 1]);
524
- }
525
-
526
- if (hasCallsLeft(callMap, spy) && calledBeforeNext) {
527
- callMap[spy.id] += 1;
528
- return true;
529
- }
530
-
531
- return false;
532
- }
533
-
534
- /**
535
- * A Sinon proxy object (fake, spy, stub)
536
- *
537
- * @typedef {object} SinonProxy
538
- * @property {Function} calledBefore - A method that determines if this proxy was called before another one
539
- * @property {string} id - Some id
540
- * @property {number} callCount - Number of times this proxy has been called
541
- */
542
-
543
- /**
544
- * Returns true when the spies have been called in the order they were supplied in
545
- *
546
- * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments
547
- * @returns {boolean} true when spies are called in order, false otherwise
548
- */
549
- function calledInOrder(spies) {
550
- var callMap = {};
551
- // eslint-disable-next-line no-underscore-dangle
552
- var _spies = arguments.length > 1 ? arguments : spies;
553
-
554
- return every$1(_spies, checkAdjacentCalls.bind(null, callMap));
555
- }
556
-
557
- var calledInOrder_1 = calledInOrder;
558
-
559
- /**
560
- * Returns a display name for a function
561
- *
562
- * @param {Function} func
563
- * @returns {string}
564
- */
565
- var functionName$1 = function functionName(func) {
566
- if (!func) {
567
- return "";
568
- }
569
-
570
- try {
571
- return (
572
- func.displayName ||
573
- func.name ||
574
- // Use function decomposition as a last resort to get function
575
- // name. Does not rely on function decomposition to work - if it
576
- // doesn't debugging will be slightly less informative
577
- // (i.e. toString will say 'spy' rather than 'myFunc').
578
- (String(func).match(/function ([^\s(]+)/) || [])[1]
579
- );
580
- } catch (e) {
581
- // Stringify may fail and we might get an exception, as a last-last
582
- // resort fall back to empty string.
583
- return "";
584
- }
585
- };
586
-
587
- var functionName = functionName$1;
588
-
589
- /**
590
- * Returns a display name for a value from a constructor
591
- *
592
- * @param {object} value A value to examine
593
- * @returns {(string|null)} A string or null
594
- */
595
- function className(value) {
596
- return (
597
- (value.constructor && value.constructor.name) ||
598
- // The next branch is for IE11 support only:
599
- // Because the name property is not set on the prototype
600
- // of the Function object, we finally try to grab the
601
- // name from its definition. This will never be reached
602
- // in node, so we are not able to test this properly.
603
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
604
- (typeof value.constructor === "function" &&
605
- /* istanbul ignore next */
606
- functionName(value.constructor)) ||
607
- null
608
- );
609
- }
610
-
611
- var className_1 = className;
612
-
613
- var deprecated = {};
614
-
615
- /* eslint-disable no-console */
616
-
617
- (function (exports) {
618
-
619
- /**
620
- * Returns a function that will invoke the supplied function and print a
621
- * deprecation warning to the console each time it is called.
622
- *
623
- * @param {Function} func
624
- * @param {string} msg
625
- * @returns {Function}
626
- */
627
- exports.wrap = function (func, msg) {
628
- var wrapped = function () {
629
- exports.printWarning(msg);
630
- return func.apply(this, arguments);
631
- };
632
- if (func.prototype) {
633
- wrapped.prototype = func.prototype;
634
- }
635
- return wrapped;
636
- };
637
-
638
- /**
639
- * Returns a string which can be supplied to `wrap()` to notify the user that a
640
- * particular part of the sinon API has been deprecated.
641
- *
642
- * @param {string} packageName
643
- * @param {string} funcName
644
- * @returns {string}
645
- */
646
- exports.defaultMsg = function (packageName, funcName) {
647
- return `${packageName}.${funcName} is deprecated and will be removed from the public API in a future version of ${packageName}.`;
648
- };
649
-
650
- /**
651
- * Prints a warning on the console, when it exists
652
- *
653
- * @param {string} msg
654
- * @returns {undefined}
655
- */
656
- exports.printWarning = function (msg) {
657
- /* istanbul ignore next */
658
- if (typeof process === "object" && process.emitWarning) {
659
- // Emit Warnings in Node
660
- process.emitWarning(msg);
661
- } else if (console.info) {
662
- console.info(msg);
663
- } else {
664
- console.log(msg);
665
- }
666
- };
667
- } (deprecated));
668
-
669
- /**
670
- * Returns true when fn returns true for all members of obj.
671
- * This is an every implementation that works for all iterables
672
- *
673
- * @param {object} obj
674
- * @param {Function} fn
675
- * @returns {boolean}
676
- */
677
- var every = function every(obj, fn) {
678
- var pass = true;
679
-
680
- try {
681
- // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
682
- obj.forEach(function () {
683
- if (!fn.apply(this, arguments)) {
684
- // Throwing an error is the only way to break `forEach`
685
- throw new Error();
686
- }
687
- });
688
- } catch (e) {
689
- pass = false;
690
- }
691
-
692
- return pass;
693
- };
694
-
695
- var sort = array.sort;
696
- var slice = array.slice;
697
-
698
- /**
699
- * @private
700
- */
701
- function comparator(a, b) {
702
- // uuid, won't ever be equal
703
- var aCall = a.getCall(0);
704
- var bCall = b.getCall(0);
705
- var aId = (aCall && aCall.callId) || -1;
706
- var bId = (bCall && bCall.callId) || -1;
707
-
708
- return aId < bId ? -1 : 1;
709
- }
710
-
711
- /**
712
- * A Sinon proxy object (fake, spy, stub)
713
- *
714
- * @typedef {object} SinonProxy
715
- * @property {Function} getCall - A method that can return the first call
716
- */
717
-
718
- /**
719
- * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call
720
- *
721
- * @param {SinonProxy[] | SinonProxy} spies
722
- * @returns {SinonProxy[]}
723
- */
724
- function orderByFirstCall(spies) {
725
- return sort(slice(spies), comparator);
726
- }
727
-
728
- var orderByFirstCall_1 = orderByFirstCall;
729
-
730
- var copyPrototype$4 = copyPrototypeMethods;
731
-
732
- var _function = copyPrototype$4(Function.prototype);
733
-
734
- var copyPrototype$3 = copyPrototypeMethods;
735
-
736
- var map = copyPrototype$3(Map.prototype);
737
-
738
- var copyPrototype$2 = copyPrototypeMethods;
739
-
740
- var object = copyPrototype$2(Object.prototype);
741
-
742
- var copyPrototype$1 = copyPrototypeMethods;
743
-
744
- var set = copyPrototype$1(Set.prototype);
745
-
746
- var copyPrototype = copyPrototypeMethods;
747
-
748
- var string = copyPrototype(String.prototype);
749
-
750
- var prototypes = {
751
- array: array,
752
- function: _function,
753
- map: map,
754
- object: object,
755
- set: set,
756
- string: string,
757
- };
758
-
759
- var typeDetect = {exports: {}};
760
-
761
- (function (module, exports) {
762
- (function (global, factory) {
763
- module.exports = factory() ;
764
- }(commonjsGlobal, (function () {
765
- /* !
766
- * type-detect
767
- * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
768
- * MIT Licensed
769
- */
770
- var promiseExists = typeof Promise === 'function';
771
-
772
- /* eslint-disable no-undef */
773
- var globalObject = typeof self === 'object' ? self : commonjsGlobal; // eslint-disable-line id-blacklist
774
-
775
- var symbolExists = typeof Symbol !== 'undefined';
776
- var mapExists = typeof Map !== 'undefined';
777
- var setExists = typeof Set !== 'undefined';
778
- var weakMapExists = typeof WeakMap !== 'undefined';
779
- var weakSetExists = typeof WeakSet !== 'undefined';
780
- var dataViewExists = typeof DataView !== 'undefined';
781
- var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined';
782
- var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined';
783
- var setEntriesExists = setExists && typeof Set.prototype.entries === 'function';
784
- var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function';
785
- var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries());
786
- var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries());
787
- var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function';
788
- var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]());
789
- var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function';
790
- var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]());
791
- var toStringLeftSliceLength = 8;
792
- var toStringRightSliceLength = -1;
793
- /**
794
- * ### typeOf (obj)
795
- *
796
- * Uses `Object.prototype.toString` to determine the type of an object,
797
- * normalising behaviour across engine versions & well optimised.
798
- *
799
- * @param {Mixed} object
800
- * @return {String} object type
801
- * @api public
802
- */
803
- function typeDetect(obj) {
804
- /* ! Speed optimisation
805
- * Pre:
806
- * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled)
807
- * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled)
808
- * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled)
809
- * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled)
810
- * function x 2,556,769 ops/sec ±1.73% (77 runs sampled)
811
- * Post:
812
- * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled)
813
- * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled)
814
- * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled)
815
- * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled)
816
- * function x 31,296,870 ops/sec ±0.96% (83 runs sampled)
817
- */
818
- var typeofObj = typeof obj;
819
- if (typeofObj !== 'object') {
820
- return typeofObj;
821
- }
822
-
823
- /* ! Speed optimisation
824
- * Pre:
825
- * null x 28,645,765 ops/sec ±1.17% (82 runs sampled)
826
- * Post:
827
- * null x 36,428,962 ops/sec ±1.37% (84 runs sampled)
828
- */
829
- if (obj === null) {
830
- return 'null';
831
- }
832
-
833
- /* ! Spec Conformance
834
- * Test: `Object.prototype.toString.call(window)``
835
- * - Node === "[object global]"
836
- * - Chrome === "[object global]"
837
- * - Firefox === "[object Window]"
838
- * - PhantomJS === "[object Window]"
839
- * - Safari === "[object Window]"
840
- * - IE 11 === "[object Window]"
841
- * - IE Edge === "[object Window]"
842
- * Test: `Object.prototype.toString.call(this)``
843
- * - Chrome Worker === "[object global]"
844
- * - Firefox Worker === "[object DedicatedWorkerGlobalScope]"
845
- * - Safari Worker === "[object DedicatedWorkerGlobalScope]"
846
- * - IE 11 Worker === "[object WorkerGlobalScope]"
847
- * - IE Edge Worker === "[object WorkerGlobalScope]"
848
- */
849
- if (obj === globalObject) {
850
- return 'global';
851
- }
852
-
853
- /* ! Speed optimisation
854
- * Pre:
855
- * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled)
856
- * Post:
857
- * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled)
858
- */
859
- if (
860
- Array.isArray(obj) &&
861
- (symbolToStringTagExists === false || !(Symbol.toStringTag in obj))
862
- ) {
863
- return 'Array';
864
- }
865
-
866
- // Not caching existence of `window` and related properties due to potential
867
- // for `window` to be unset before tests in quasi-browser environments.
868
- if (typeof window === 'object' && window !== null) {
869
- /* ! Spec Conformance
870
- * (https://html.spec.whatwg.org/multipage/browsers.html#location)
871
- * WhatWG HTML$7.7.3 - The `Location` interface
872
- * Test: `Object.prototype.toString.call(window.location)``
873
- * - IE <=11 === "[object Object]"
874
- * - IE Edge <=13 === "[object Object]"
875
- */
876
- if (typeof window.location === 'object' && obj === window.location) {
877
- return 'Location';
878
- }
879
-
880
- /* ! Spec Conformance
881
- * (https://html.spec.whatwg.org/#document)
882
- * WhatWG HTML$3.1.1 - The `Document` object
883
- * Note: Most browsers currently adher to the W3C DOM Level 2 spec
884
- * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268)
885
- * which suggests that browsers should use HTMLTableCellElement for
886
- * both TD and TH elements. WhatWG separates these.
887
- * WhatWG HTML states:
888
- * > For historical reasons, Window objects must also have a
889
- * > writable, configurable, non-enumerable property named
890
- * > HTMLDocument whose value is the Document interface object.
891
- * Test: `Object.prototype.toString.call(document)``
892
- * - Chrome === "[object HTMLDocument]"
893
- * - Firefox === "[object HTMLDocument]"
894
- * - Safari === "[object HTMLDocument]"
895
- * - IE <=10 === "[object Document]"
896
- * - IE 11 === "[object HTMLDocument]"
897
- * - IE Edge <=13 === "[object HTMLDocument]"
898
- */
899
- if (typeof window.document === 'object' && obj === window.document) {
900
- return 'Document';
901
- }
902
-
903
- if (typeof window.navigator === 'object') {
904
- /* ! Spec Conformance
905
- * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray)
906
- * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray
907
- * Test: `Object.prototype.toString.call(navigator.mimeTypes)``
908
- * - IE <=10 === "[object MSMimeTypesCollection]"
909
- */
910
- if (typeof window.navigator.mimeTypes === 'object' &&
911
- obj === window.navigator.mimeTypes) {
912
- return 'MimeTypeArray';
913
- }
914
-
915
- /* ! Spec Conformance
916
- * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
917
- * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray
918
- * Test: `Object.prototype.toString.call(navigator.plugins)``
919
- * - IE <=10 === "[object MSPluginsCollection]"
920
- */
921
- if (typeof window.navigator.plugins === 'object' &&
922
- obj === window.navigator.plugins) {
923
- return 'PluginArray';
924
- }
925
- }
926
-
927
- if ((typeof window.HTMLElement === 'function' ||
928
- typeof window.HTMLElement === 'object') &&
929
- obj instanceof window.HTMLElement) {
930
- /* ! Spec Conformance
931
- * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
932
- * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement`
933
- * Test: `Object.prototype.toString.call(document.createElement('blockquote'))``
934
- * - IE <=10 === "[object HTMLBlockElement]"
935
- */
936
- if (obj.tagName === 'BLOCKQUOTE') {
937
- return 'HTMLQuoteElement';
938
- }
939
-
940
- /* ! Spec Conformance
941
- * (https://html.spec.whatwg.org/#htmltabledatacellelement)
942
- * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement`
943
- * Note: Most browsers currently adher to the W3C DOM Level 2 spec
944
- * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
945
- * which suggests that browsers should use HTMLTableCellElement for
946
- * both TD and TH elements. WhatWG separates these.
947
- * Test: Object.prototype.toString.call(document.createElement('td'))
948
- * - Chrome === "[object HTMLTableCellElement]"
949
- * - Firefox === "[object HTMLTableCellElement]"
950
- * - Safari === "[object HTMLTableCellElement]"
951
- */
952
- if (obj.tagName === 'TD') {
953
- return 'HTMLTableDataCellElement';
954
- }
955
-
956
- /* ! Spec Conformance
957
- * (https://html.spec.whatwg.org/#htmltableheadercellelement)
958
- * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement`
959
- * Note: Most browsers currently adher to the W3C DOM Level 2 spec
960
- * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
961
- * which suggests that browsers should use HTMLTableCellElement for
962
- * both TD and TH elements. WhatWG separates these.
963
- * Test: Object.prototype.toString.call(document.createElement('th'))
964
- * - Chrome === "[object HTMLTableCellElement]"
965
- * - Firefox === "[object HTMLTableCellElement]"
966
- * - Safari === "[object HTMLTableCellElement]"
967
- */
968
- if (obj.tagName === 'TH') {
969
- return 'HTMLTableHeaderCellElement';
970
- }
971
- }
972
- }
973
-
974
- /* ! Speed optimisation
975
- * Pre:
976
- * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled)
977
- * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled)
978
- * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled)
979
- * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled)
980
- * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled)
981
- * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled)
982
- * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled)
983
- * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled)
984
- * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled)
985
- * Post:
986
- * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled)
987
- * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled)
988
- * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled)
989
- * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled)
990
- * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled)
991
- * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled)
992
- * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled)
993
- * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled)
994
- * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled)
995
- */
996
- var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]);
997
- if (typeof stringTag === 'string') {
998
- return stringTag;
999
- }
1000
-
1001
- var objPrototype = Object.getPrototypeOf(obj);
1002
- /* ! Speed optimisation
1003
- * Pre:
1004
- * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled)
1005
- * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled)
1006
- * Post:
1007
- * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled)
1008
- * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled)
1009
- */
1010
- if (objPrototype === RegExp.prototype) {
1011
- return 'RegExp';
1012
- }
1013
-
1014
- /* ! Speed optimisation
1015
- * Pre:
1016
- * date x 2,130,074 ops/sec ±4.42% (68 runs sampled)
1017
- * Post:
1018
- * date x 3,953,779 ops/sec ±1.35% (77 runs sampled)
1019
- */
1020
- if (objPrototype === Date.prototype) {
1021
- return 'Date';
1022
- }
1023
-
1024
- /* ! Spec Conformance
1025
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag)
1026
- * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise":
1027
- * Test: `Object.prototype.toString.call(Promise.resolve())``
1028
- * - Chrome <=47 === "[object Object]"
1029
- * - Edge <=20 === "[object Object]"
1030
- * - Firefox 29-Latest === "[object Promise]"
1031
- * - Safari 7.1-Latest === "[object Promise]"
1032
- */
1033
- if (promiseExists && objPrototype === Promise.prototype) {
1034
- return 'Promise';
1035
- }
1036
-
1037
- /* ! Speed optimisation
1038
- * Pre:
1039
- * set x 2,222,186 ops/sec ±1.31% (82 runs sampled)
1040
- * Post:
1041
- * set x 4,545,879 ops/sec ±1.13% (83 runs sampled)
1042
- */
1043
- if (setExists && objPrototype === Set.prototype) {
1044
- return 'Set';
1045
- }
1046
-
1047
- /* ! Speed optimisation
1048
- * Pre:
1049
- * map x 2,396,842 ops/sec ±1.59% (81 runs sampled)
1050
- * Post:
1051
- * map x 4,183,945 ops/sec ±6.59% (82 runs sampled)
1052
- */
1053
- if (mapExists && objPrototype === Map.prototype) {
1054
- return 'Map';
1055
- }
1056
-
1057
- /* ! Speed optimisation
1058
- * Pre:
1059
- * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled)
1060
- * Post:
1061
- * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled)
1062
- */
1063
- if (weakSetExists && objPrototype === WeakSet.prototype) {
1064
- return 'WeakSet';
1065
- }
1066
-
1067
- /* ! Speed optimisation
1068
- * Pre:
1069
- * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled)
1070
- * Post:
1071
- * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled)
1072
- */
1073
- if (weakMapExists && objPrototype === WeakMap.prototype) {
1074
- return 'WeakMap';
1075
- }
1076
-
1077
- /* ! Spec Conformance
1078
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag)
1079
- * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView":
1080
- * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))``
1081
- * - Edge <=13 === "[object Object]"
1082
- */
1083
- if (dataViewExists && objPrototype === DataView.prototype) {
1084
- return 'DataView';
1085
- }
1086
-
1087
- /* ! Spec Conformance
1088
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag)
1089
- * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator":
1090
- * Test: `Object.prototype.toString.call(new Map().entries())``
1091
- * - Edge <=13 === "[object Object]"
1092
- */
1093
- if (mapExists && objPrototype === mapIteratorPrototype) {
1094
- return 'Map Iterator';
1095
- }
1096
-
1097
- /* ! Spec Conformance
1098
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag)
1099
- * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator":
1100
- * Test: `Object.prototype.toString.call(new Set().entries())``
1101
- * - Edge <=13 === "[object Object]"
1102
- */
1103
- if (setExists && objPrototype === setIteratorPrototype) {
1104
- return 'Set Iterator';
1105
- }
1106
-
1107
- /* ! Spec Conformance
1108
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag)
1109
- * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator":
1110
- * Test: `Object.prototype.toString.call([][Symbol.iterator]())``
1111
- * - Edge <=13 === "[object Object]"
1112
- */
1113
- if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) {
1114
- return 'Array Iterator';
1115
- }
1116
-
1117
- /* ! Spec Conformance
1118
- * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag)
1119
- * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator":
1120
- * Test: `Object.prototype.toString.call(''[Symbol.iterator]())``
1121
- * - Edge <=13 === "[object Object]"
1122
- */
1123
- if (stringIteratorExists && objPrototype === stringIteratorPrototype) {
1124
- return 'String Iterator';
1125
- }
1126
-
1127
- /* ! Speed optimisation
1128
- * Pre:
1129
- * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled)
1130
- * Post:
1131
- * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled)
1132
- */
1133
- if (objPrototype === null) {
1134
- return 'Object';
1135
- }
1136
-
1137
- return Object
1138
- .prototype
1139
- .toString
1140
- .call(obj)
1141
- .slice(toStringLeftSliceLength, toStringRightSliceLength);
1142
- }
1143
-
1144
- return typeDetect;
1145
-
1146
- })));
1147
- } (typeDetect));
1148
-
1149
- var typeDetectExports = typeDetect.exports;
1150
-
1151
- var type = typeDetectExports;
1152
-
1153
- /**
1154
- * Returns the lower-case result of running type from type-detect on the value
1155
- *
1156
- * @param {*} value
1157
- * @returns {string}
1158
- */
1159
- var typeOf = function typeOf(value) {
1160
- return type(value).toLowerCase();
1161
- };
1162
-
1163
- /**
1164
- * Returns a string representation of the value
1165
- *
1166
- * @param {*} value
1167
- * @returns {string}
1168
- */
1169
- function valueToString(value) {
1170
- if (value && value.toString) {
1171
- // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
1172
- return value.toString();
1173
- }
1174
- return String(value);
1175
- }
1176
-
1177
- var valueToString_1 = valueToString;
1178
-
1179
- var lib = {
1180
- global: global,
1181
- calledInOrder: calledInOrder_1,
1182
- className: className_1,
1183
- deprecated: deprecated,
1184
- every: every,
1185
- functionName: functionName$1,
1186
- orderByFirstCall: orderByFirstCall_1,
1187
- prototypes: prototypes,
1188
- typeOf: typeOf,
1189
- valueToString: valueToString_1,
1190
- };
1191
-
1192
- (function (module, exports) {
1193
-
1194
- const globalObject = lib.global;
1195
- let timersModule;
1196
- if (typeof commonjsRequire === "function" && 'object' === "object") {
1197
- try {
1198
- timersModule = require("timers");
1199
- } catch (e) {
1200
- // ignored
1201
- }
1202
- }
1203
-
1204
- /**
1205
- * @typedef {object} IdleDeadline
1206
- * @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout
1207
- * @property {function():number} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period
1208
- */
1209
-
1210
- /**
1211
- * Queues a function to be called during a browser's idle periods
1212
- *
1213
- * @callback RequestIdleCallback
1214
- * @param {function(IdleDeadline)} callback
1215
- * @param {{timeout: number}} options - an options object
1216
- * @returns {number} the id
1217
- */
1218
-
1219
- /**
1220
- * @callback NextTick
1221
- * @param {VoidVarArgsFunc} callback - the callback to run
1222
- * @param {...*} arguments - optional arguments to call the callback with
1223
- * @returns {void}
1224
- */
1225
-
1226
- /**
1227
- * @callback SetImmediate
1228
- * @param {VoidVarArgsFunc} callback - the callback to run
1229
- * @param {...*} arguments - optional arguments to call the callback with
1230
- * @returns {NodeImmediate}
1231
- */
1232
-
1233
- /**
1234
- * @callback VoidVarArgsFunc
1235
- * @param {...*} callback - the callback to run
1236
- * @returns {void}
1237
- */
1238
-
1239
- /**
1240
- * @typedef RequestAnimationFrame
1241
- * @property {function(number):void} requestAnimationFrame
1242
- * @returns {number} - the id
1243
- */
1244
-
1245
- /**
1246
- * @typedef Performance
1247
- * @property {function(): number} now
1248
- */
1249
-
1250
- /* eslint-disable jsdoc/require-property-description */
1251
- /**
1252
- * @typedef {object} Clock
1253
- * @property {number} now - the current time
1254
- * @property {Date} Date - the Date constructor
1255
- * @property {number} loopLimit - the maximum number of timers before assuming an infinite loop
1256
- * @property {RequestIdleCallback} requestIdleCallback
1257
- * @property {function(number):void} cancelIdleCallback
1258
- * @property {setTimeout} setTimeout
1259
- * @property {clearTimeout} clearTimeout
1260
- * @property {NextTick} nextTick
1261
- * @property {queueMicrotask} queueMicrotask
1262
- * @property {setInterval} setInterval
1263
- * @property {clearInterval} clearInterval
1264
- * @property {SetImmediate} setImmediate
1265
- * @property {function(NodeImmediate):void} clearImmediate
1266
- * @property {function():number} countTimers
1267
- * @property {RequestAnimationFrame} requestAnimationFrame
1268
- * @property {function(number):void} cancelAnimationFrame
1269
- * @property {function():void} runMicrotasks
1270
- * @property {function(string | number): number} tick
1271
- * @property {function(string | number): Promise<number>} tickAsync
1272
- * @property {function(): number} next
1273
- * @property {function(): Promise<number>} nextAsync
1274
- * @property {function(): number} runAll
1275
- * @property {function(): number} runToFrame
1276
- * @property {function(): Promise<number>} runAllAsync
1277
- * @property {function(): number} runToLast
1278
- * @property {function(): Promise<number>} runToLastAsync
1279
- * @property {function(): void} reset
1280
- * @property {function(number | Date): void} setSystemTime
1281
- * @property {function(number): void} jump
1282
- * @property {Performance} performance
1283
- * @property {function(number[]): number[]} hrtime - process.hrtime (legacy)
1284
- * @property {function(): void} uninstall Uninstall the clock.
1285
- * @property {Function[]} methods - the methods that are faked
1286
- * @property {boolean} [shouldClearNativeTimers] inherited from config
1287
- * @property {{methodName:string, original:any}[] | undefined} timersModuleMethods
1288
- */
1289
- /* eslint-enable jsdoc/require-property-description */
1290
-
1291
- /**
1292
- * Configuration object for the `install` method.
1293
- *
1294
- * @typedef {object} Config
1295
- * @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch)
1296
- * @property {string[]} [toFake] names of the methods that should be faked.
1297
- * @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll()
1298
- * @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false)
1299
- * @property {number} [advanceTimeDelta] increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
1300
- * @property {boolean} [shouldClearNativeTimers] forwards clear timer calls to native functions if they are not fakes (default: false)
1301
- */
1302
-
1303
- /* eslint-disable jsdoc/require-property-description */
1304
- /**
1305
- * The internal structure to describe a scheduled fake timer
1306
- *
1307
- * @typedef {object} Timer
1308
- * @property {Function} func
1309
- * @property {*[]} args
1310
- * @property {number} delay
1311
- * @property {number} callAt
1312
- * @property {number} createdAt
1313
- * @property {boolean} immediate
1314
- * @property {number} id
1315
- * @property {Error} [error]
1316
- */
1317
-
1318
- /**
1319
- * A Node timer
1320
- *
1321
- * @typedef {object} NodeImmediate
1322
- * @property {function(): boolean} hasRef
1323
- * @property {function(): NodeImmediate} ref
1324
- * @property {function(): NodeImmediate} unref
1325
- */
1326
- /* eslint-enable jsdoc/require-property-description */
1327
-
1328
- /* eslint-disable complexity */
1329
-
1330
- /**
1331
- * Mocks available features in the specified global namespace.
1332
- *
1333
- * @param {*} _global Namespace to mock (e.g. `window`)
1334
- * @returns {FakeTimers}
1335
- */
1336
- function withGlobal(_global) {
1337
- const userAgent = _global.navigator && _global.navigator.userAgent;
1338
- const isRunningInIE = userAgent && userAgent.indexOf("MSIE ") > -1;
1339
- const maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
1340
- const idCounterStart = 1e12; // arbitrarily large number to avoid collisions with native timer IDs
1341
- const NOOP = function () {
1342
- return undefined;
1343
- };
1344
- const NOOP_ARRAY = function () {
1345
- return [];
1346
- };
1347
- const timeoutResult = _global.setTimeout(NOOP, 0);
1348
- const addTimerReturnsObject = typeof timeoutResult === "object";
1349
- const hrtimePresent =
1350
- _global.process && typeof _global.process.hrtime === "function";
1351
- const hrtimeBigintPresent =
1352
- hrtimePresent && typeof _global.process.hrtime.bigint === "function";
1353
- const nextTickPresent =
1354
- _global.process && typeof _global.process.nextTick === "function";
1355
- const utilPromisify = _global.process && require$$2.promisify;
1356
- const performancePresent =
1357
- _global.performance && typeof _global.performance.now === "function";
1358
- const hasPerformancePrototype =
1359
- _global.Performance &&
1360
- (typeof _global.Performance).match(/^(function|object)$/);
1361
- const hasPerformanceConstructorPrototype =
1362
- _global.performance &&
1363
- _global.performance.constructor &&
1364
- _global.performance.constructor.prototype;
1365
- const queueMicrotaskPresent = _global.hasOwnProperty("queueMicrotask");
1366
- const requestAnimationFramePresent =
1367
- _global.requestAnimationFrame &&
1368
- typeof _global.requestAnimationFrame === "function";
1369
- const cancelAnimationFramePresent =
1370
- _global.cancelAnimationFrame &&
1371
- typeof _global.cancelAnimationFrame === "function";
1372
- const requestIdleCallbackPresent =
1373
- _global.requestIdleCallback &&
1374
- typeof _global.requestIdleCallback === "function";
1375
- const cancelIdleCallbackPresent =
1376
- _global.cancelIdleCallback &&
1377
- typeof _global.cancelIdleCallback === "function";
1378
- const setImmediatePresent =
1379
- _global.setImmediate && typeof _global.setImmediate === "function";
1380
-
1381
- // Make properties writable in IE, as per
1382
- // https://www.adequatelygood.com/Replacing-setTimeout-Globally.html
1383
- /* eslint-disable no-self-assign */
1384
- if (isRunningInIE) {
1385
- _global.setTimeout = _global.setTimeout;
1386
- _global.clearTimeout = _global.clearTimeout;
1387
- _global.setInterval = _global.setInterval;
1388
- _global.clearInterval = _global.clearInterval;
1389
- _global.Date = _global.Date;
1390
- }
1391
-
1392
- // setImmediate is not a standard function
1393
- // avoid adding the prop to the window object if not present
1394
- if (setImmediatePresent) {
1395
- _global.setImmediate = _global.setImmediate;
1396
- _global.clearImmediate = _global.clearImmediate;
1397
- }
1398
- /* eslint-enable no-self-assign */
1399
-
1400
- _global.clearTimeout(timeoutResult);
1401
-
1402
- const NativeDate = _global.Date;
1403
- let uniqueTimerId = idCounterStart;
1404
-
1405
- /**
1406
- * @param {number} num
1407
- * @returns {boolean}
1408
- */
1409
- function isNumberFinite(num) {
1410
- if (Number.isFinite) {
1411
- return Number.isFinite(num);
1412
- }
1413
-
1414
- return isFinite(num);
1415
- }
1416
-
1417
- let isNearInfiniteLimit = false;
1418
-
1419
- /**
1420
- * @param {Clock} clock
1421
- * @param {number} i
1422
- */
1423
- function checkIsNearInfiniteLimit(clock, i) {
1424
- if (clock.loopLimit && i === clock.loopLimit - 1) {
1425
- isNearInfiniteLimit = true;
1426
- }
1427
- }
1428
-
1429
- /**
1430
- *
1431
- */
1432
- function resetIsNearInfiniteLimit() {
1433
- isNearInfiniteLimit = false;
1434
- }
1435
-
1436
- /**
1437
- * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
1438
- * number of milliseconds. This is used to support human-readable strings passed
1439
- * to clock.tick()
1440
- *
1441
- * @param {string} str
1442
- * @returns {number}
1443
- */
1444
- function parseTime(str) {
1445
- if (!str) {
1446
- return 0;
1447
- }
1448
-
1449
- const strings = str.split(":");
1450
- const l = strings.length;
1451
- let i = l;
1452
- let ms = 0;
1453
- let parsed;
1454
-
1455
- if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
1456
- throw new Error(
1457
- "tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits"
1458
- );
1459
- }
1460
-
1461
- while (i--) {
1462
- parsed = parseInt(strings[i], 10);
1463
-
1464
- if (parsed >= 60) {
1465
- throw new Error(`Invalid time ${str}`);
1466
- }
1467
-
1468
- ms += parsed * Math.pow(60, l - i - 1);
1469
- }
1470
-
1471
- return ms * 1000;
1472
- }
1473
-
1474
- /**
1475
- * Get the decimal part of the millisecond value as nanoseconds
1476
- *
1477
- * @param {number} msFloat the number of milliseconds
1478
- * @returns {number} an integer number of nanoseconds in the range [0,1e6)
1479
- *
1480
- * Example: nanoRemainer(123.456789) -> 456789
1481
- */
1482
- function nanoRemainder(msFloat) {
1483
- const modulo = 1e6;
1484
- const remainder = (msFloat * 1e6) % modulo;
1485
- const positiveRemainder =
1486
- remainder < 0 ? remainder + modulo : remainder;
1487
-
1488
- return Math.floor(positiveRemainder);
1489
- }
1490
-
1491
- /**
1492
- * Used to grok the `now` parameter to createClock.
1493
- *
1494
- * @param {Date|number} epoch the system time
1495
- * @returns {number}
1496
- */
1497
- function getEpoch(epoch) {
1498
- if (!epoch) {
1499
- return 0;
1500
- }
1501
- if (typeof epoch.getTime === "function") {
1502
- return epoch.getTime();
1503
- }
1504
- if (typeof epoch === "number") {
1505
- return epoch;
1506
- }
1507
- throw new TypeError("now should be milliseconds since UNIX epoch");
1508
- }
1509
-
1510
- /**
1511
- * @param {number} from
1512
- * @param {number} to
1513
- * @param {Timer} timer
1514
- * @returns {boolean}
1515
- */
1516
- function inRange(from, to, timer) {
1517
- return timer && timer.callAt >= from && timer.callAt <= to;
1518
- }
1519
-
1520
- /**
1521
- * @param {Clock} clock
1522
- * @param {Timer} job
1523
- */
1524
- function getInfiniteLoopError(clock, job) {
1525
- const infiniteLoopError = new Error(
1526
- `Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!`
1527
- );
1528
-
1529
- if (!job.error) {
1530
- return infiniteLoopError;
1531
- }
1532
-
1533
- // pattern never matched in Node
1534
- const computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/;
1535
- let clockMethodPattern = new RegExp(
1536
- String(Object.keys(clock).join("|"))
1537
- );
1538
-
1539
- if (addTimerReturnsObject) {
1540
- // node.js environment
1541
- clockMethodPattern = new RegExp(
1542
- `\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+`
1543
- );
1544
- }
1545
-
1546
- let matchedLineIndex = -1;
1547
- job.error.stack.split("\n").some(function (line, i) {
1548
- // If we've matched a computed target line (e.g. setTimeout) then we
1549
- // don't need to look any further. Return true to stop iterating.
1550
- const matchedComputedTarget = line.match(computedTargetPattern);
1551
- /* istanbul ignore if */
1552
- if (matchedComputedTarget) {
1553
- matchedLineIndex = i;
1554
- return true;
1555
- }
1556
-
1557
- // If we've matched a clock method line, then there may still be
1558
- // others further down the trace. Return false to keep iterating.
1559
- const matchedClockMethod = line.match(clockMethodPattern);
1560
- if (matchedClockMethod) {
1561
- matchedLineIndex = i;
1562
- return false;
1563
- }
1564
-
1565
- // If we haven't matched anything on this line, but we matched
1566
- // previously and set the matched line index, then we can stop.
1567
- // If we haven't matched previously, then we should keep iterating.
1568
- return matchedLineIndex >= 0;
1569
- });
1570
-
1571
- const stack = `${infiniteLoopError}\n${job.type || "Microtask"} - ${
1572
- job.func.name || "anonymous"
1573
- }\n${job.error.stack
1574
- .split("\n")
1575
- .slice(matchedLineIndex + 1)
1576
- .join("\n")}`;
1577
-
1578
- try {
1579
- Object.defineProperty(infiniteLoopError, "stack", {
1580
- value: stack,
1581
- });
1582
- } catch (e) {
1583
- // noop
1584
- }
1585
-
1586
- return infiniteLoopError;
1587
- }
1588
-
1589
- /**
1590
- * @param {Date} target
1591
- * @param {Date} source
1592
- * @returns {Date} the target after modifications
1593
- */
1594
- function mirrorDateProperties(target, source) {
1595
- let prop;
1596
- for (prop in source) {
1597
- if (source.hasOwnProperty(prop)) {
1598
- target[prop] = source[prop];
1599
- }
1600
- }
1601
-
1602
- // set special now implementation
1603
- if (source.now) {
1604
- target.now = function now() {
1605
- return target.clock.now;
1606
- };
1607
- } else {
1608
- delete target.now;
1609
- }
1610
-
1611
- // set special toSource implementation
1612
- if (source.toSource) {
1613
- target.toSource = function toSource() {
1614
- return source.toSource();
1615
- };
1616
- } else {
1617
- delete target.toSource;
1618
- }
1619
-
1620
- // set special toString implementation
1621
- target.toString = function toString() {
1622
- return source.toString();
1623
- };
1624
-
1625
- target.prototype = source.prototype;
1626
- target.parse = source.parse;
1627
- target.UTC = source.UTC;
1628
- target.prototype.toUTCString = source.prototype.toUTCString;
1629
- target.isFake = true;
1630
-
1631
- return target;
1632
- }
1633
-
1634
- //eslint-disable-next-line jsdoc/require-jsdoc
1635
- function createDate() {
1636
- /**
1637
- * @param {number} year
1638
- * @param {number} month
1639
- * @param {number} date
1640
- * @param {number} hour
1641
- * @param {number} minute
1642
- * @param {number} second
1643
- * @param {number} ms
1644
- * @returns {Date}
1645
- */
1646
- function ClockDate(year, month, date, hour, minute, second, ms) {
1647
- // the Date constructor called as a function, ref Ecma-262 Edition 5.1, section 15.9.2.
1648
- // This remains so in the 10th edition of 2019 as well.
1649
- if (!(this instanceof ClockDate)) {
1650
- return new NativeDate(ClockDate.clock.now).toString();
1651
- }
1652
-
1653
- // if Date is called as a constructor with 'new' keyword
1654
- // Defensive and verbose to avoid potential harm in passing
1655
- // explicit undefined when user does not pass argument
1656
- switch (arguments.length) {
1657
- case 0:
1658
- return new NativeDate(ClockDate.clock.now);
1659
- case 1:
1660
- return new NativeDate(year);
1661
- case 2:
1662
- return new NativeDate(year, month);
1663
- case 3:
1664
- return new NativeDate(year, month, date);
1665
- case 4:
1666
- return new NativeDate(year, month, date, hour);
1667
- case 5:
1668
- return new NativeDate(year, month, date, hour, minute);
1669
- case 6:
1670
- return new NativeDate(
1671
- year,
1672
- month,
1673
- date,
1674
- hour,
1675
- minute,
1676
- second
1677
- );
1678
- default:
1679
- return new NativeDate(
1680
- year,
1681
- month,
1682
- date,
1683
- hour,
1684
- minute,
1685
- second,
1686
- ms
1687
- );
1688
- }
1689
- }
1690
-
1691
- return mirrorDateProperties(ClockDate, NativeDate);
1692
- }
1693
-
1694
- //eslint-disable-next-line jsdoc/require-jsdoc
1695
- function enqueueJob(clock, job) {
1696
- // enqueues a microtick-deferred task - ecma262/#sec-enqueuejob
1697
- if (!clock.jobs) {
1698
- clock.jobs = [];
1699
- }
1700
- clock.jobs.push(job);
1701
- }
1702
-
1703
- //eslint-disable-next-line jsdoc/require-jsdoc
1704
- function runJobs(clock) {
1705
- // runs all microtick-deferred tasks - ecma262/#sec-runjobs
1706
- if (!clock.jobs) {
1707
- return;
1708
- }
1709
- for (let i = 0; i < clock.jobs.length; i++) {
1710
- const job = clock.jobs[i];
1711
- job.func.apply(null, job.args);
1712
-
1713
- checkIsNearInfiniteLimit(clock, i);
1714
- if (clock.loopLimit && i > clock.loopLimit) {
1715
- throw getInfiniteLoopError(clock, job);
1716
- }
1717
- }
1718
- resetIsNearInfiniteLimit();
1719
- clock.jobs = [];
1720
- }
1721
-
1722
- /**
1723
- * @param {Clock} clock
1724
- * @param {Timer} timer
1725
- * @returns {number} id of the created timer
1726
- */
1727
- function addTimer(clock, timer) {
1728
- if (timer.func === undefined) {
1729
- throw new Error("Callback must be provided to timer calls");
1730
- }
1731
-
1732
- if (addTimerReturnsObject) {
1733
- // Node.js environment
1734
- if (typeof timer.func !== "function") {
1735
- throw new TypeError(
1736
- `[ERR_INVALID_CALLBACK]: Callback must be a function. Received ${
1737
- timer.func
1738
- } of type ${typeof timer.func}`
1739
- );
1740
- }
1741
- }
1742
-
1743
- if (isNearInfiniteLimit) {
1744
- timer.error = new Error();
1745
- }
1746
-
1747
- timer.type = timer.immediate ? "Immediate" : "Timeout";
1748
-
1749
- if (timer.hasOwnProperty("delay")) {
1750
- if (typeof timer.delay !== "number") {
1751
- timer.delay = parseInt(timer.delay, 10);
1752
- }
1753
-
1754
- if (!isNumberFinite(timer.delay)) {
1755
- timer.delay = 0;
1756
- }
1757
- timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
1758
- timer.delay = Math.max(0, timer.delay);
1759
- }
1760
-
1761
- if (timer.hasOwnProperty("interval")) {
1762
- timer.type = "Interval";
1763
- timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
1764
- }
1765
-
1766
- if (timer.hasOwnProperty("animation")) {
1767
- timer.type = "AnimationFrame";
1768
- timer.animation = true;
1769
- }
1770
-
1771
- if (timer.hasOwnProperty("idleCallback")) {
1772
- timer.type = "IdleCallback";
1773
- timer.idleCallback = true;
1774
- }
1775
-
1776
- if (!clock.timers) {
1777
- clock.timers = {};
1778
- }
1779
-
1780
- timer.id = uniqueTimerId++;
1781
- timer.createdAt = clock.now;
1782
- timer.callAt =
1783
- clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1784
-
1785
- clock.timers[timer.id] = timer;
1786
-
1787
- if (addTimerReturnsObject) {
1788
- const res = {
1789
- refed: true,
1790
- ref: function () {
1791
- this.refed = true;
1792
- return res;
1793
- },
1794
- unref: function () {
1795
- this.refed = false;
1796
- return res;
1797
- },
1798
- hasRef: function () {
1799
- return this.refed;
1800
- },
1801
- refresh: function () {
1802
- timer.callAt =
1803
- clock.now +
1804
- (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1805
-
1806
- // it _might_ have been removed, but if not the assignment is perfectly fine
1807
- clock.timers[timer.id] = timer;
1808
-
1809
- return res;
1810
- },
1811
- [Symbol.toPrimitive]: function () {
1812
- return timer.id;
1813
- },
1814
- };
1815
- return res;
1816
- }
1817
-
1818
- return timer.id;
1819
- }
1820
-
1821
- /* eslint consistent-return: "off" */
1822
- /**
1823
- * Timer comparitor
1824
- *
1825
- * @param {Timer} a
1826
- * @param {Timer} b
1827
- * @returns {number}
1828
- */
1829
- function compareTimers(a, b) {
1830
- // Sort first by absolute timing
1831
- if (a.callAt < b.callAt) {
1832
- return -1;
1833
- }
1834
- if (a.callAt > b.callAt) {
1835
- return 1;
1836
- }
1837
-
1838
- // Sort next by immediate, immediate timers take precedence
1839
- if (a.immediate && !b.immediate) {
1840
- return -1;
1841
- }
1842
- if (!a.immediate && b.immediate) {
1843
- return 1;
1844
- }
1845
-
1846
- // Sort next by creation time, earlier-created timers take precedence
1847
- if (a.createdAt < b.createdAt) {
1848
- return -1;
1849
- }
1850
- if (a.createdAt > b.createdAt) {
1851
- return 1;
1852
- }
1853
-
1854
- // Sort next by id, lower-id timers take precedence
1855
- if (a.id < b.id) {
1856
- return -1;
1857
- }
1858
- if (a.id > b.id) {
1859
- return 1;
1860
- }
1861
-
1862
- // As timer ids are unique, no fallback `0` is necessary
1863
- }
1864
-
1865
- /**
1866
- * @param {Clock} clock
1867
- * @param {number} from
1868
- * @param {number} to
1869
- * @returns {Timer}
1870
- */
1871
- function firstTimerInRange(clock, from, to) {
1872
- const timers = clock.timers;
1873
- let timer = null;
1874
- let id, isInRange;
1875
-
1876
- for (id in timers) {
1877
- if (timers.hasOwnProperty(id)) {
1878
- isInRange = inRange(from, to, timers[id]);
1879
-
1880
- if (
1881
- isInRange &&
1882
- (!timer || compareTimers(timer, timers[id]) === 1)
1883
- ) {
1884
- timer = timers[id];
1885
- }
1886
- }
1887
- }
1888
-
1889
- return timer;
1890
- }
1891
-
1892
- /**
1893
- * @param {Clock} clock
1894
- * @returns {Timer}
1895
- */
1896
- function firstTimer(clock) {
1897
- const timers = clock.timers;
1898
- let timer = null;
1899
- let id;
1900
-
1901
- for (id in timers) {
1902
- if (timers.hasOwnProperty(id)) {
1903
- if (!timer || compareTimers(timer, timers[id]) === 1) {
1904
- timer = timers[id];
1905
- }
1906
- }
1907
- }
1908
-
1909
- return timer;
1910
- }
1911
-
1912
- /**
1913
- * @param {Clock} clock
1914
- * @returns {Timer}
1915
- */
1916
- function lastTimer(clock) {
1917
- const timers = clock.timers;
1918
- let timer = null;
1919
- let id;
1920
-
1921
- for (id in timers) {
1922
- if (timers.hasOwnProperty(id)) {
1923
- if (!timer || compareTimers(timer, timers[id]) === -1) {
1924
- timer = timers[id];
1925
- }
1926
- }
1927
- }
1928
-
1929
- return timer;
1930
- }
1931
-
1932
- /**
1933
- * @param {Clock} clock
1934
- * @param {Timer} timer
1935
- */
1936
- function callTimer(clock, timer) {
1937
- if (typeof timer.interval === "number") {
1938
- clock.timers[timer.id].callAt += timer.interval;
1939
- } else {
1940
- delete clock.timers[timer.id];
1941
- }
1942
-
1943
- if (typeof timer.func === "function") {
1944
- timer.func.apply(null, timer.args);
1945
- } else {
1946
- /* eslint no-eval: "off" */
1947
- const eval2 = eval;
1948
- (function () {
1949
- eval2(timer.func);
1950
- })();
1951
- }
1952
- }
1953
-
1954
- /**
1955
- * Gets clear handler name for a given timer type
1956
- *
1957
- * @param {string} ttype
1958
- */
1959
- function getClearHandler(ttype) {
1960
- if (ttype === "IdleCallback" || ttype === "AnimationFrame") {
1961
- return `cancel${ttype}`;
1962
- }
1963
- return `clear${ttype}`;
1964
- }
1965
-
1966
- /**
1967
- * Gets schedule handler name for a given timer type
1968
- *
1969
- * @param {string} ttype
1970
- */
1971
- function getScheduleHandler(ttype) {
1972
- if (ttype === "IdleCallback" || ttype === "AnimationFrame") {
1973
- return `request${ttype}`;
1974
- }
1975
- return `set${ttype}`;
1976
- }
1977
-
1978
- /**
1979
- * Creates an anonymous function to warn only once
1980
- */
1981
- function createWarnOnce() {
1982
- let calls = 0;
1983
- return function (msg) {
1984
- // eslint-disable-next-line
1985
- !calls++ && console.warn(msg);
1986
- };
1987
- }
1988
- const warnOnce = createWarnOnce();
1989
-
1990
- /**
1991
- * @param {Clock} clock
1992
- * @param {number} timerId
1993
- * @param {string} ttype
1994
- */
1995
- function clearTimer(clock, timerId, ttype) {
1996
- if (!timerId) {
1997
- // null appears to be allowed in most browsers, and appears to be
1998
- // relied upon by some libraries, like Bootstrap carousel
1999
- return;
2000
- }
2001
-
2002
- if (!clock.timers) {
2003
- clock.timers = {};
2004
- }
2005
-
2006
- // in Node, the ID is stored as the primitive value for `Timeout` objects
2007
- // for `Immediate` objects, no ID exists, so it gets coerced to NaN
2008
- const id = Number(timerId);
2009
-
2010
- if (Number.isNaN(id) || id < idCounterStart) {
2011
- const handlerName = getClearHandler(ttype);
2012
-
2013
- if (clock.shouldClearNativeTimers === true) {
2014
- const nativeHandler = clock[`_${handlerName}`];
2015
- return typeof nativeHandler === "function"
2016
- ? nativeHandler(timerId)
2017
- : undefined;
2018
- }
2019
- warnOnce(
2020
- `FakeTimers: ${handlerName} was invoked to clear a native timer instead of one created by this library.` +
2021
- "\nTo automatically clean-up native timers, use `shouldClearNativeTimers`."
2022
- );
2023
- }
2024
-
2025
- if (clock.timers.hasOwnProperty(id)) {
2026
- // check that the ID matches a timer of the correct type
2027
- const timer = clock.timers[id];
2028
- if (
2029
- timer.type === ttype ||
2030
- (timer.type === "Timeout" && ttype === "Interval") ||
2031
- (timer.type === "Interval" && ttype === "Timeout")
2032
- ) {
2033
- delete clock.timers[id];
2034
- } else {
2035
- const clear = getClearHandler(ttype);
2036
- const schedule = getScheduleHandler(timer.type);
2037
- throw new Error(
2038
- `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`
2039
- );
2040
- }
2041
- }
2042
- }
2043
-
2044
- /**
2045
- * @param {Clock} clock
2046
- * @param {Config} config
2047
- * @returns {Timer[]}
2048
- */
2049
- function uninstall(clock, config) {
2050
- let method, i, l;
2051
- const installedHrTime = "_hrtime";
2052
- const installedNextTick = "_nextTick";
2053
-
2054
- for (i = 0, l = clock.methods.length; i < l; i++) {
2055
- method = clock.methods[i];
2056
- if (method === "hrtime" && _global.process) {
2057
- _global.process.hrtime = clock[installedHrTime];
2058
- } else if (method === "nextTick" && _global.process) {
2059
- _global.process.nextTick = clock[installedNextTick];
2060
- } else if (method === "performance") {
2061
- const originalPerfDescriptor = Object.getOwnPropertyDescriptor(
2062
- clock,
2063
- `_${method}`
2064
- );
2065
- if (
2066
- originalPerfDescriptor &&
2067
- originalPerfDescriptor.get &&
2068
- !originalPerfDescriptor.set
2069
- ) {
2070
- Object.defineProperty(
2071
- _global,
2072
- method,
2073
- originalPerfDescriptor
2074
- );
2075
- } else if (originalPerfDescriptor.configurable) {
2076
- _global[method] = clock[`_${method}`];
2077
- }
2078
- } else {
2079
- if (_global[method] && _global[method].hadOwnProperty) {
2080
- _global[method] = clock[`_${method}`];
2081
- } else {
2082
- try {
2083
- delete _global[method];
2084
- } catch (ignore) {
2085
- /* eslint no-empty: "off" */
2086
- }
2087
- }
2088
- }
2089
- if (clock.timersModuleMethods !== undefined) {
2090
- for (let j = 0; j < clock.timersModuleMethods.length; j++) {
2091
- const entry = clock.timersModuleMethods[j];
2092
- timersModule[entry.methodName] = entry.original;
2093
- }
2094
- }
2095
- }
2096
-
2097
- if (config.shouldAdvanceTime === true) {
2098
- _global.clearInterval(clock.attachedInterval);
2099
- }
2100
-
2101
- // Prevent multiple executions which will completely remove these props
2102
- clock.methods = [];
2103
-
2104
- // return pending timers, to enable checking what timers remained on uninstall
2105
- if (!clock.timers) {
2106
- return [];
2107
- }
2108
- return Object.keys(clock.timers).map(function mapper(key) {
2109
- return clock.timers[key];
2110
- });
2111
- }
2112
-
2113
- /**
2114
- * @param {object} target the target containing the method to replace
2115
- * @param {string} method the keyname of the method on the target
2116
- * @param {Clock} clock
2117
- */
2118
- function hijackMethod(target, method, clock) {
2119
- clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(
2120
- target,
2121
- method
2122
- );
2123
- clock[`_${method}`] = target[method];
2124
-
2125
- if (method === "Date") {
2126
- const date = mirrorDateProperties(clock[method], target[method]);
2127
- target[method] = date;
2128
- } else if (method === "performance") {
2129
- const originalPerfDescriptor = Object.getOwnPropertyDescriptor(
2130
- target,
2131
- method
2132
- );
2133
- // JSDOM has a read only performance field so we have to save/copy it differently
2134
- if (
2135
- originalPerfDescriptor &&
2136
- originalPerfDescriptor.get &&
2137
- !originalPerfDescriptor.set
2138
- ) {
2139
- Object.defineProperty(
2140
- clock,
2141
- `_${method}`,
2142
- originalPerfDescriptor
2143
- );
2144
-
2145
- const perfDescriptor = Object.getOwnPropertyDescriptor(
2146
- clock,
2147
- method
2148
- );
2149
- Object.defineProperty(target, method, perfDescriptor);
2150
- } else {
2151
- target[method] = clock[method];
2152
- }
2153
- } else {
2154
- target[method] = function () {
2155
- return clock[method].apply(clock, arguments);
2156
- };
2157
-
2158
- Object.defineProperties(
2159
- target[method],
2160
- Object.getOwnPropertyDescriptors(clock[method])
2161
- );
2162
- }
2163
-
2164
- target[method].clock = clock;
2165
- }
2166
-
2167
- /**
2168
- * @param {Clock} clock
2169
- * @param {number} advanceTimeDelta
2170
- */
2171
- function doIntervalTick(clock, advanceTimeDelta) {
2172
- clock.tick(advanceTimeDelta);
2173
- }
2174
-
2175
- /**
2176
- * @typedef {object} Timers
2177
- * @property {setTimeout} setTimeout
2178
- * @property {clearTimeout} clearTimeout
2179
- * @property {setInterval} setInterval
2180
- * @property {clearInterval} clearInterval
2181
- * @property {Date} Date
2182
- * @property {SetImmediate=} setImmediate
2183
- * @property {function(NodeImmediate): void=} clearImmediate
2184
- * @property {function(number[]):number[]=} hrtime
2185
- * @property {NextTick=} nextTick
2186
- * @property {Performance=} performance
2187
- * @property {RequestAnimationFrame=} requestAnimationFrame
2188
- * @property {boolean=} queueMicrotask
2189
- * @property {function(number): void=} cancelAnimationFrame
2190
- * @property {RequestIdleCallback=} requestIdleCallback
2191
- * @property {function(number): void=} cancelIdleCallback
2192
- */
2193
-
2194
- /** @type {Timers} */
2195
- const timers = {
2196
- setTimeout: _global.setTimeout,
2197
- clearTimeout: _global.clearTimeout,
2198
- setInterval: _global.setInterval,
2199
- clearInterval: _global.clearInterval,
2200
- Date: _global.Date,
2201
- };
2202
-
2203
- if (setImmediatePresent) {
2204
- timers.setImmediate = _global.setImmediate;
2205
- timers.clearImmediate = _global.clearImmediate;
2206
- }
2207
-
2208
- if (hrtimePresent) {
2209
- timers.hrtime = _global.process.hrtime;
2210
- }
2211
-
2212
- if (nextTickPresent) {
2213
- timers.nextTick = _global.process.nextTick;
2214
- }
2215
-
2216
- if (performancePresent) {
2217
- timers.performance = _global.performance;
2218
- }
2219
-
2220
- if (requestAnimationFramePresent) {
2221
- timers.requestAnimationFrame = _global.requestAnimationFrame;
2222
- }
2223
-
2224
- if (queueMicrotaskPresent) {
2225
- timers.queueMicrotask = true;
2226
- }
2227
-
2228
- if (cancelAnimationFramePresent) {
2229
- timers.cancelAnimationFrame = _global.cancelAnimationFrame;
2230
- }
2231
-
2232
- if (requestIdleCallbackPresent) {
2233
- timers.requestIdleCallback = _global.requestIdleCallback;
2234
- }
2235
-
2236
- if (cancelIdleCallbackPresent) {
2237
- timers.cancelIdleCallback = _global.cancelIdleCallback;
2238
- }
2239
-
2240
- const originalSetTimeout = _global.setImmediate || _global.setTimeout;
2241
-
2242
- /**
2243
- * @param {Date|number} [start] the system time - non-integer values are floored
2244
- * @param {number} [loopLimit] maximum number of timers that will be run when calling runAll()
2245
- * @returns {Clock}
2246
- */
2247
- function createClock(start, loopLimit) {
2248
- // eslint-disable-next-line no-param-reassign
2249
- start = Math.floor(getEpoch(start));
2250
- // eslint-disable-next-line no-param-reassign
2251
- loopLimit = loopLimit || 1000;
2252
- let nanos = 0;
2253
- const adjustedSystemTime = [0, 0]; // [millis, nanoremainder]
2254
-
2255
- if (NativeDate === undefined) {
2256
- throw new Error(
2257
- "The global scope doesn't have a `Date` object" +
2258
- " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)"
2259
- );
2260
- }
2261
-
2262
- const clock = {
2263
- now: start,
2264
- Date: createDate(),
2265
- loopLimit: loopLimit,
2266
- };
2267
-
2268
- clock.Date.clock = clock;
2269
-
2270
- //eslint-disable-next-line jsdoc/require-jsdoc
2271
- function getTimeToNextFrame() {
2272
- return 16 - ((clock.now - start) % 16);
2273
- }
2274
-
2275
- //eslint-disable-next-line jsdoc/require-jsdoc
2276
- function hrtime(prev) {
2277
- const millisSinceStart = clock.now - adjustedSystemTime[0] - start;
2278
- const secsSinceStart = Math.floor(millisSinceStart / 1000);
2279
- const remainderInNanos =
2280
- (millisSinceStart - secsSinceStart * 1e3) * 1e6 +
2281
- nanos -
2282
- adjustedSystemTime[1];
2283
-
2284
- if (Array.isArray(prev)) {
2285
- if (prev[1] > 1e9) {
2286
- throw new TypeError(
2287
- "Number of nanoseconds can't exceed a billion"
2288
- );
2289
- }
2290
-
2291
- const oldSecs = prev[0];
2292
- let nanoDiff = remainderInNanos - prev[1];
2293
- let secDiff = secsSinceStart - oldSecs;
2294
-
2295
- if (nanoDiff < 0) {
2296
- nanoDiff += 1e9;
2297
- secDiff -= 1;
2298
- }
2299
-
2300
- return [secDiff, nanoDiff];
2301
- }
2302
- return [secsSinceStart, remainderInNanos];
2303
- }
2304
-
2305
- function fakePerformanceNow() {
2306
- const hrt = hrtime();
2307
- const millis = hrt[0] * 1000 + hrt[1] / 1e6;
2308
- return millis;
2309
- }
2310
-
2311
- if (hrtimeBigintPresent) {
2312
- hrtime.bigint = function () {
2313
- const parts = hrtime();
2314
- return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]); // eslint-disable-line
2315
- };
2316
- }
2317
-
2318
- clock.requestIdleCallback = function requestIdleCallback(
2319
- func,
2320
- timeout
2321
- ) {
2322
- let timeToNextIdlePeriod = 0;
2323
-
2324
- if (clock.countTimers() > 0) {
2325
- timeToNextIdlePeriod = 50; // const for now
2326
- }
2327
-
2328
- const result = addTimer(clock, {
2329
- func: func,
2330
- args: Array.prototype.slice.call(arguments, 2),
2331
- delay:
2332
- typeof timeout === "undefined"
2333
- ? timeToNextIdlePeriod
2334
- : Math.min(timeout, timeToNextIdlePeriod),
2335
- idleCallback: true,
2336
- });
2337
-
2338
- return Number(result);
2339
- };
2340
-
2341
- clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
2342
- return clearTimer(clock, timerId, "IdleCallback");
2343
- };
2344
-
2345
- clock.setTimeout = function setTimeout(func, timeout) {
2346
- return addTimer(clock, {
2347
- func: func,
2348
- args: Array.prototype.slice.call(arguments, 2),
2349
- delay: timeout,
2350
- });
2351
- };
2352
- if (typeof _global.Promise !== "undefined" && utilPromisify) {
2353
- clock.setTimeout[utilPromisify.custom] =
2354
- function promisifiedSetTimeout(timeout, arg) {
2355
- return new _global.Promise(function setTimeoutExecutor(
2356
- resolve
2357
- ) {
2358
- addTimer(clock, {
2359
- func: resolve,
2360
- args: [arg],
2361
- delay: timeout,
2362
- });
2363
- });
2364
- };
2365
- }
2366
-
2367
- clock.clearTimeout = function clearTimeout(timerId) {
2368
- return clearTimer(clock, timerId, "Timeout");
2369
- };
2370
-
2371
- clock.nextTick = function nextTick(func) {
2372
- return enqueueJob(clock, {
2373
- func: func,
2374
- args: Array.prototype.slice.call(arguments, 1),
2375
- error: isNearInfiniteLimit ? new Error() : null,
2376
- });
2377
- };
2378
-
2379
- clock.queueMicrotask = function queueMicrotask(func) {
2380
- return clock.nextTick(func); // explicitly drop additional arguments
2381
- };
2382
-
2383
- clock.setInterval = function setInterval(func, timeout) {
2384
- // eslint-disable-next-line no-param-reassign
2385
- timeout = parseInt(timeout, 10);
2386
- return addTimer(clock, {
2387
- func: func,
2388
- args: Array.prototype.slice.call(arguments, 2),
2389
- delay: timeout,
2390
- interval: timeout,
2391
- });
2392
- };
2393
-
2394
- clock.clearInterval = function clearInterval(timerId) {
2395
- return clearTimer(clock, timerId, "Interval");
2396
- };
2397
-
2398
- if (setImmediatePresent) {
2399
- clock.setImmediate = function setImmediate(func) {
2400
- return addTimer(clock, {
2401
- func: func,
2402
- args: Array.prototype.slice.call(arguments, 1),
2403
- immediate: true,
2404
- });
2405
- };
2406
-
2407
- if (typeof _global.Promise !== "undefined" && utilPromisify) {
2408
- clock.setImmediate[utilPromisify.custom] =
2409
- function promisifiedSetImmediate(arg) {
2410
- return new _global.Promise(
2411
- function setImmediateExecutor(resolve) {
2412
- addTimer(clock, {
2413
- func: resolve,
2414
- args: [arg],
2415
- immediate: true,
2416
- });
2417
- }
2418
- );
2419
- };
2420
- }
2421
-
2422
- clock.clearImmediate = function clearImmediate(timerId) {
2423
- return clearTimer(clock, timerId, "Immediate");
2424
- };
2425
- }
2426
-
2427
- clock.countTimers = function countTimers() {
2428
- return (
2429
- Object.keys(clock.timers || {}).length +
2430
- (clock.jobs || []).length
2431
- );
2432
- };
2433
-
2434
- clock.requestAnimationFrame = function requestAnimationFrame(func) {
2435
- const result = addTimer(clock, {
2436
- func: func,
2437
- delay: getTimeToNextFrame(),
2438
- get args() {
2439
- return [fakePerformanceNow()];
2440
- },
2441
- animation: true,
2442
- });
2443
-
2444
- return Number(result);
2445
- };
2446
-
2447
- clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
2448
- return clearTimer(clock, timerId, "AnimationFrame");
2449
- };
2450
-
2451
- clock.runMicrotasks = function runMicrotasks() {
2452
- runJobs(clock);
2453
- };
2454
-
2455
- /**
2456
- * @param {number|string} tickValue milliseconds or a string parseable by parseTime
2457
- * @param {boolean} isAsync
2458
- * @param {Function} resolve
2459
- * @param {Function} reject
2460
- * @returns {number|undefined} will return the new `now` value or nothing for async
2461
- */
2462
- function doTick(tickValue, isAsync, resolve, reject) {
2463
- const msFloat =
2464
- typeof tickValue === "number"
2465
- ? tickValue
2466
- : parseTime(tickValue);
2467
- const ms = Math.floor(msFloat);
2468
- const remainder = nanoRemainder(msFloat);
2469
- let nanosTotal = nanos + remainder;
2470
- let tickTo = clock.now + ms;
2471
-
2472
- if (msFloat < 0) {
2473
- throw new TypeError("Negative ticks are not supported");
2474
- }
2475
-
2476
- // adjust for positive overflow
2477
- if (nanosTotal >= 1e6) {
2478
- tickTo += 1;
2479
- nanosTotal -= 1e6;
2480
- }
2481
-
2482
- nanos = nanosTotal;
2483
- let tickFrom = clock.now;
2484
- let previous = clock.now;
2485
- // ESLint fails to detect this correctly
2486
- /* eslint-disable prefer-const */
2487
- let timer,
2488
- firstException,
2489
- oldNow,
2490
- nextPromiseTick,
2491
- compensationCheck,
2492
- postTimerCall;
2493
- /* eslint-enable prefer-const */
2494
-
2495
- clock.duringTick = true;
2496
-
2497
- // perform microtasks
2498
- oldNow = clock.now;
2499
- runJobs(clock);
2500
- if (oldNow !== clock.now) {
2501
- // compensate for any setSystemTime() call during microtask callback
2502
- tickFrom += clock.now - oldNow;
2503
- tickTo += clock.now - oldNow;
2504
- }
2505
-
2506
- //eslint-disable-next-line jsdoc/require-jsdoc
2507
- function doTickInner() {
2508
- // perform each timer in the requested range
2509
- timer = firstTimerInRange(clock, tickFrom, tickTo);
2510
- // eslint-disable-next-line no-unmodified-loop-condition
2511
- while (timer && tickFrom <= tickTo) {
2512
- if (clock.timers[timer.id]) {
2513
- tickFrom = timer.callAt;
2514
- clock.now = timer.callAt;
2515
- oldNow = clock.now;
2516
- try {
2517
- runJobs(clock);
2518
- callTimer(clock, timer);
2519
- } catch (e) {
2520
- firstException = firstException || e;
2521
- }
2522
-
2523
- if (isAsync) {
2524
- // finish up after native setImmediate callback to allow
2525
- // all native es6 promises to process their callbacks after
2526
- // each timer fires.
2527
- originalSetTimeout(nextPromiseTick);
2528
- return;
2529
- }
2530
-
2531
- compensationCheck();
2532
- }
2533
-
2534
- postTimerCall();
2535
- }
2536
-
2537
- // perform process.nextTick()s again
2538
- oldNow = clock.now;
2539
- runJobs(clock);
2540
- if (oldNow !== clock.now) {
2541
- // compensate for any setSystemTime() call during process.nextTick() callback
2542
- tickFrom += clock.now - oldNow;
2543
- tickTo += clock.now - oldNow;
2544
- }
2545
- clock.duringTick = false;
2546
-
2547
- // corner case: during runJobs new timers were scheduled which could be in the range [clock.now, tickTo]
2548
- timer = firstTimerInRange(clock, tickFrom, tickTo);
2549
- if (timer) {
2550
- try {
2551
- clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range
2552
- } catch (e) {
2553
- firstException = firstException || e;
2554
- }
2555
- } else {
2556
- // no timers remaining in the requested range: move the clock all the way to the end
2557
- clock.now = tickTo;
2558
-
2559
- // update nanos
2560
- nanos = nanosTotal;
2561
- }
2562
- if (firstException) {
2563
- throw firstException;
2564
- }
2565
-
2566
- if (isAsync) {
2567
- resolve(clock.now);
2568
- } else {
2569
- return clock.now;
2570
- }
2571
- }
2572
-
2573
- nextPromiseTick =
2574
- isAsync &&
2575
- function () {
2576
- try {
2577
- compensationCheck();
2578
- postTimerCall();
2579
- doTickInner();
2580
- } catch (e) {
2581
- reject(e);
2582
- }
2583
- };
2584
-
2585
- compensationCheck = function () {
2586
- // compensate for any setSystemTime() call during timer callback
2587
- if (oldNow !== clock.now) {
2588
- tickFrom += clock.now - oldNow;
2589
- tickTo += clock.now - oldNow;
2590
- previous += clock.now - oldNow;
2591
- }
2592
- };
2593
-
2594
- postTimerCall = function () {
2595
- timer = firstTimerInRange(clock, previous, tickTo);
2596
- previous = tickFrom;
2597
- };
2598
-
2599
- return doTickInner();
2600
- }
2601
-
2602
- /**
2603
- * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2604
- * @returns {number} will return the new `now` value
2605
- */
2606
- clock.tick = function tick(tickValue) {
2607
- return doTick(tickValue, false);
2608
- };
2609
-
2610
- if (typeof _global.Promise !== "undefined") {
2611
- /**
2612
- * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2613
- * @returns {Promise}
2614
- */
2615
- clock.tickAsync = function tickAsync(tickValue) {
2616
- return new _global.Promise(function (resolve, reject) {
2617
- originalSetTimeout(function () {
2618
- try {
2619
- doTick(tickValue, true, resolve, reject);
2620
- } catch (e) {
2621
- reject(e);
2622
- }
2623
- });
2624
- });
2625
- };
2626
- }
2627
-
2628
- clock.next = function next() {
2629
- runJobs(clock);
2630
- const timer = firstTimer(clock);
2631
- if (!timer) {
2632
- return clock.now;
2633
- }
2634
-
2635
- clock.duringTick = true;
2636
- try {
2637
- clock.now = timer.callAt;
2638
- callTimer(clock, timer);
2639
- runJobs(clock);
2640
- return clock.now;
2641
- } finally {
2642
- clock.duringTick = false;
2643
- }
2644
- };
2645
-
2646
- if (typeof _global.Promise !== "undefined") {
2647
- clock.nextAsync = function nextAsync() {
2648
- return new _global.Promise(function (resolve, reject) {
2649
- originalSetTimeout(function () {
2650
- try {
2651
- const timer = firstTimer(clock);
2652
- if (!timer) {
2653
- resolve(clock.now);
2654
- return;
2655
- }
2656
-
2657
- let err;
2658
- clock.duringTick = true;
2659
- clock.now = timer.callAt;
2660
- try {
2661
- callTimer(clock, timer);
2662
- } catch (e) {
2663
- err = e;
2664
- }
2665
- clock.duringTick = false;
2666
-
2667
- originalSetTimeout(function () {
2668
- if (err) {
2669
- reject(err);
2670
- } else {
2671
- resolve(clock.now);
2672
- }
2673
- });
2674
- } catch (e) {
2675
- reject(e);
2676
- }
2677
- });
2678
- });
2679
- };
2680
- }
2681
-
2682
- clock.runAll = function runAll() {
2683
- let numTimers, i;
2684
- runJobs(clock);
2685
- for (i = 0; i < clock.loopLimit; i++) {
2686
- if (!clock.timers) {
2687
- resetIsNearInfiniteLimit();
2688
- return clock.now;
2689
- }
2690
-
2691
- numTimers = Object.keys(clock.timers).length;
2692
- if (numTimers === 0) {
2693
- resetIsNearInfiniteLimit();
2694
- return clock.now;
2695
- }
2696
-
2697
- clock.next();
2698
- checkIsNearInfiniteLimit(clock, i);
2699
- }
2700
-
2701
- const excessJob = firstTimer(clock);
2702
- throw getInfiniteLoopError(clock, excessJob);
2703
- };
2704
-
2705
- clock.runToFrame = function runToFrame() {
2706
- return clock.tick(getTimeToNextFrame());
2707
- };
2708
-
2709
- if (typeof _global.Promise !== "undefined") {
2710
- clock.runAllAsync = function runAllAsync() {
2711
- return new _global.Promise(function (resolve, reject) {
2712
- let i = 0;
2713
- /**
2714
- *
2715
- */
2716
- function doRun() {
2717
- originalSetTimeout(function () {
2718
- try {
2719
- let numTimers;
2720
- if (i < clock.loopLimit) {
2721
- if (!clock.timers) {
2722
- resetIsNearInfiniteLimit();
2723
- resolve(clock.now);
2724
- return;
2725
- }
2726
-
2727
- numTimers = Object.keys(
2728
- clock.timers
2729
- ).length;
2730
- if (numTimers === 0) {
2731
- resetIsNearInfiniteLimit();
2732
- resolve(clock.now);
2733
- return;
2734
- }
2735
-
2736
- clock.next();
2737
-
2738
- i++;
2739
-
2740
- doRun();
2741
- checkIsNearInfiniteLimit(clock, i);
2742
- return;
2743
- }
2744
-
2745
- const excessJob = firstTimer(clock);
2746
- reject(getInfiniteLoopError(clock, excessJob));
2747
- } catch (e) {
2748
- reject(e);
2749
- }
2750
- });
2751
- }
2752
- doRun();
2753
- });
2754
- };
2755
- }
2756
-
2757
- clock.runToLast = function runToLast() {
2758
- const timer = lastTimer(clock);
2759
- if (!timer) {
2760
- runJobs(clock);
2761
- return clock.now;
2762
- }
2763
-
2764
- return clock.tick(timer.callAt - clock.now);
2765
- };
2766
-
2767
- if (typeof _global.Promise !== "undefined") {
2768
- clock.runToLastAsync = function runToLastAsync() {
2769
- return new _global.Promise(function (resolve, reject) {
2770
- originalSetTimeout(function () {
2771
- try {
2772
- const timer = lastTimer(clock);
2773
- if (!timer) {
2774
- resolve(clock.now);
2775
- }
2776
-
2777
- resolve(clock.tickAsync(timer.callAt - clock.now));
2778
- } catch (e) {
2779
- reject(e);
2780
- }
2781
- });
2782
- });
2783
- };
2784
- }
2785
-
2786
- clock.reset = function reset() {
2787
- nanos = 0;
2788
- clock.timers = {};
2789
- clock.jobs = [];
2790
- clock.now = start;
2791
- };
2792
-
2793
- clock.setSystemTime = function setSystemTime(systemTime) {
2794
- // determine time difference
2795
- const newNow = getEpoch(systemTime);
2796
- const difference = newNow - clock.now;
2797
- let id, timer;
2798
-
2799
- adjustedSystemTime[0] = adjustedSystemTime[0] + difference;
2800
- adjustedSystemTime[1] = adjustedSystemTime[1] + nanos;
2801
- // update 'system clock'
2802
- clock.now = newNow;
2803
- nanos = 0;
2804
-
2805
- // update timers and intervals to keep them stable
2806
- for (id in clock.timers) {
2807
- if (clock.timers.hasOwnProperty(id)) {
2808
- timer = clock.timers[id];
2809
- timer.createdAt += difference;
2810
- timer.callAt += difference;
2811
- }
2812
- }
2813
- };
2814
-
2815
- /**
2816
- * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2817
- * @returns {number} will return the new `now` value
2818
- */
2819
- clock.jump = function jump(tickValue) {
2820
- const msFloat =
2821
- typeof tickValue === "number"
2822
- ? tickValue
2823
- : parseTime(tickValue);
2824
- const ms = Math.floor(msFloat);
2825
-
2826
- for (const timer of Object.values(clock.timers)) {
2827
- if (clock.now + ms > timer.callAt) {
2828
- timer.callAt = clock.now + ms;
2829
- }
2830
- }
2831
- clock.tick(ms);
2832
- };
2833
-
2834
- if (performancePresent) {
2835
- clock.performance = Object.create(null);
2836
- clock.performance.now = fakePerformanceNow;
2837
- }
2838
-
2839
- if (hrtimePresent) {
2840
- clock.hrtime = hrtime;
2841
- }
2842
-
2843
- return clock;
2844
- }
2845
-
2846
- /* eslint-disable complexity */
2847
-
2848
- /**
2849
- * @param {Config=} [config] Optional config
2850
- * @returns {Clock}
2851
- */
2852
- function install(config) {
2853
- if (
2854
- arguments.length > 1 ||
2855
- config instanceof Date ||
2856
- Array.isArray(config) ||
2857
- typeof config === "number"
2858
- ) {
2859
- throw new TypeError(
2860
- `FakeTimers.install called with ${String(
2861
- config
2862
- )} install requires an object parameter`
2863
- );
2864
- }
2865
-
2866
- if (_global.Date.isFake === true) {
2867
- // Timers are already faked; this is a problem.
2868
- // Make the user reset timers before continuing.
2869
- throw new TypeError(
2870
- "Can't install fake timers twice on the same global object."
2871
- );
2872
- }
2873
-
2874
- // eslint-disable-next-line no-param-reassign
2875
- config = typeof config !== "undefined" ? config : {};
2876
- config.shouldAdvanceTime = config.shouldAdvanceTime || false;
2877
- config.advanceTimeDelta = config.advanceTimeDelta || 20;
2878
- config.shouldClearNativeTimers =
2879
- config.shouldClearNativeTimers || false;
2880
-
2881
- if (config.target) {
2882
- throw new TypeError(
2883
- "config.target is no longer supported. Use `withGlobal(target)` instead."
2884
- );
2885
- }
2886
-
2887
- let i, l;
2888
- const clock = createClock(config.now, config.loopLimit);
2889
- clock.shouldClearNativeTimers = config.shouldClearNativeTimers;
2890
-
2891
- clock.uninstall = function () {
2892
- return uninstall(clock, config);
2893
- };
2894
-
2895
- clock.methods = config.toFake || [];
2896
-
2897
- if (clock.methods.length === 0) {
2898
- // do not fake nextTick by default - GitHub#126
2899
- clock.methods = Object.keys(timers).filter(function (key) {
2900
- return key !== "nextTick" && key !== "queueMicrotask";
2901
- });
2902
- }
2903
-
2904
- if (config.shouldAdvanceTime === true) {
2905
- const intervalTick = doIntervalTick.bind(
2906
- null,
2907
- clock,
2908
- config.advanceTimeDelta
2909
- );
2910
- const intervalId = _global.setInterval(
2911
- intervalTick,
2912
- config.advanceTimeDelta
2913
- );
2914
- clock.attachedInterval = intervalId;
2915
- }
2916
-
2917
- if (clock.methods.includes("performance")) {
2918
- const proto = (() => {
2919
- if (hasPerformancePrototype) {
2920
- return _global.Performance.prototype;
2921
- }
2922
- if (hasPerformanceConstructorPrototype) {
2923
- return _global.performance.constructor.prototype;
2924
- }
2925
- })();
2926
- if (proto) {
2927
- Object.getOwnPropertyNames(proto).forEach(function (name) {
2928
- if (name !== "now") {
2929
- clock.performance[name] =
2930
- name.indexOf("getEntries") === 0
2931
- ? NOOP_ARRAY
2932
- : NOOP;
2933
- }
2934
- });
2935
- } else if ((config.toFake || []).includes("performance")) {
2936
- // user explicitly tried to fake performance when not present
2937
- throw new ReferenceError(
2938
- "non-existent performance object cannot be faked"
2939
- );
2940
- }
2941
- }
2942
- if (_global === globalObject && timersModule) {
2943
- clock.timersModuleMethods = [];
2944
- }
2945
- for (i = 0, l = clock.methods.length; i < l; i++) {
2946
- const nameOfMethodToReplace = clock.methods[i];
2947
- if (nameOfMethodToReplace === "hrtime") {
2948
- if (
2949
- _global.process &&
2950
- typeof _global.process.hrtime === "function"
2951
- ) {
2952
- hijackMethod(_global.process, nameOfMethodToReplace, clock);
2953
- }
2954
- } else if (nameOfMethodToReplace === "nextTick") {
2955
- if (
2956
- _global.process &&
2957
- typeof _global.process.nextTick === "function"
2958
- ) {
2959
- hijackMethod(_global.process, nameOfMethodToReplace, clock);
2960
- }
2961
- } else {
2962
- hijackMethod(_global, nameOfMethodToReplace, clock);
2963
- }
2964
- if (
2965
- clock.timersModuleMethods !== undefined &&
2966
- timersModule[nameOfMethodToReplace]
2967
- ) {
2968
- const original = timersModule[nameOfMethodToReplace];
2969
- clock.timersModuleMethods.push({
2970
- methodName: nameOfMethodToReplace,
2971
- original: original,
2972
- });
2973
- timersModule[nameOfMethodToReplace] =
2974
- _global[nameOfMethodToReplace];
2975
- }
2976
- }
2977
-
2978
- return clock;
2979
- }
2980
-
2981
- /* eslint-enable complexity */
2982
-
2983
- return {
2984
- timers: timers,
2985
- createClock: createClock,
2986
- install: install,
2987
- withGlobal: withGlobal,
2988
- };
2989
- }
2990
-
2991
- /**
2992
- * @typedef {object} FakeTimers
2993
- * @property {Timers} timers
2994
- * @property {createClock} createClock
2995
- * @property {Function} install
2996
- * @property {withGlobal} withGlobal
2997
- */
2998
-
2999
- /* eslint-enable complexity */
3000
-
3001
- /** @type {FakeTimers} */
3002
- const defaultImplementation = withGlobal(globalObject);
3003
-
3004
- exports.timers = defaultImplementation.timers;
3005
- exports.createClock = defaultImplementation.createClock;
3006
- exports.install = defaultImplementation.install;
3007
- exports.withGlobal = withGlobal;
3008
- } (fakeTimersSrc, fakeTimersSrc.exports));
3009
-
3010
- var fakeTimersSrcExports = fakeTimersSrc.exports;
3011
-
3012
- class FakeTimers {
3013
- _clock;
3014
- _fakingTime;
3015
- _fakingDate;
3016
- _fakeTimers;
3017
- _userConfig;
3018
- _now = RealDate.now;
3019
- constructor({
3020
- global,
3021
- config
3022
- }) {
3023
- this._userConfig = config;
3024
- this._fakingDate = false;
3025
- this._fakingTime = false;
3026
- this._fakeTimers = fakeTimersSrcExports.withGlobal(global);
3027
- }
3028
- clearAllTimers() {
3029
- if (this._fakingTime)
3030
- this._clock.reset();
3031
- }
3032
- dispose() {
3033
- this.useRealTimers();
3034
- }
3035
- runAllTimers() {
3036
- if (this._checkFakeTimers())
3037
- this._clock.runAll();
3038
- }
3039
- async runAllTimersAsync() {
3040
- if (this._checkFakeTimers())
3041
- await this._clock.runAllAsync();
3042
- }
3043
- runOnlyPendingTimers() {
3044
- if (this._checkFakeTimers())
3045
- this._clock.runToLast();
3046
- }
3047
- async runOnlyPendingTimersAsync() {
3048
- if (this._checkFakeTimers())
3049
- await this._clock.runToLastAsync();
3050
- }
3051
- advanceTimersToNextTimer(steps = 1) {
3052
- if (this._checkFakeTimers()) {
3053
- for (let i = steps; i > 0; i--) {
3054
- this._clock.next();
3055
- this._clock.tick(0);
3056
- if (this._clock.countTimers() === 0)
3057
- break;
3058
- }
3059
- }
3060
- }
3061
- async advanceTimersToNextTimerAsync(steps = 1) {
3062
- if (this._checkFakeTimers()) {
3063
- for (let i = steps; i > 0; i--) {
3064
- await this._clock.nextAsync();
3065
- this._clock.tick(0);
3066
- if (this._clock.countTimers() === 0)
3067
- break;
3068
- }
3069
- }
3070
- }
3071
- advanceTimersByTime(msToRun) {
3072
- if (this._checkFakeTimers())
3073
- this._clock.tick(msToRun);
3074
- }
3075
- async advanceTimersByTimeAsync(msToRun) {
3076
- if (this._checkFakeTimers())
3077
- await this._clock.tickAsync(msToRun);
3078
- }
3079
- runAllTicks() {
3080
- if (this._checkFakeTimers()) {
3081
- this._clock.runMicrotasks();
3082
- }
3083
- }
3084
- useRealTimers() {
3085
- if (this._fakingDate) {
3086
- resetDate();
3087
- this._fakingDate = false;
3088
- }
3089
- if (this._fakingTime) {
3090
- this._clock.uninstall();
3091
- this._fakingTime = false;
3092
- }
3093
- }
3094
- useFakeTimers() {
3095
- var _a, _b;
3096
- if (this._fakingDate) {
3097
- throw new Error(
3098
- '"setSystemTime" was called already and date was mocked. Reset timers using `vi.useRealTimers()` if you want to use fake timers again.'
3099
- );
3100
- }
3101
- if (!this._fakingTime) {
3102
- const toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick");
3103
- if (((_b = (_a = this._userConfig) == null ? void 0 : _a.toFake) == null ? void 0 : _b.includes("nextTick")) && globalThis.__vitest_worker__.isChildProcess)
3104
- throw new Error("process.nextTick cannot be mocked inside child_process");
3105
- this._clock = this._fakeTimers.install({
3106
- now: Date.now(),
3107
- toFake,
3108
- ...this._userConfig
3109
- });
3110
- this._fakingTime = true;
3111
- }
3112
- }
3113
- reset() {
3114
- if (this._checkFakeTimers()) {
3115
- const { now } = this._clock;
3116
- this._clock.reset();
3117
- this._clock.setSystemTime(now);
3118
- }
3119
- }
3120
- setSystemTime(now) {
3121
- if (this._fakingTime) {
3122
- this._clock.setSystemTime(now);
3123
- } else {
3124
- mockDate(now ?? this.getRealSystemTime());
3125
- this._fakingDate = true;
3126
- }
3127
- }
3128
- getRealSystemTime() {
3129
- return this._now();
3130
- }
3131
- getTimerCount() {
3132
- if (this._checkFakeTimers())
3133
- return this._clock.countTimers();
3134
- return 0;
3135
- }
3136
- configure(config) {
3137
- this._userConfig = config;
3138
- }
3139
- isFakeTimers() {
3140
- return this._fakingTime;
3141
- }
3142
- _checkFakeTimers() {
3143
- if (!this._fakingTime) {
3144
- throw new Error(
3145
- 'Timers are not mocked. Try calling "vi.useFakeTimers()" first.'
3146
- );
3147
- }
3148
- return this._fakingTime;
3149
- }
3150
- }
3151
-
3152
- function copyStackTrace(target, source) {
3153
- if (source.stack !== void 0)
3154
- target.stack = source.stack.replace(source.message, target.message);
3155
- return target;
3156
- }
3157
- function waitFor(callback, options = {}) {
3158
- const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
3159
- const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
3160
- const STACK_TRACE_ERROR = new Error("STACK_TRACE_ERROR");
3161
- return new Promise((resolve, reject) => {
3162
- let lastError;
3163
- let promiseStatus = "idle";
3164
- let timeoutId;
3165
- let intervalId;
3166
- const onResolve = (result) => {
3167
- if (timeoutId)
3168
- clearTimeout(timeoutId);
3169
- if (intervalId)
3170
- clearInterval(intervalId);
3171
- resolve(result);
3172
- };
3173
- const handleTimeout = () => {
3174
- let error = lastError;
3175
- if (!error)
3176
- error = copyStackTrace(new Error("Timed out in waitFor!"), STACK_TRACE_ERROR);
3177
- reject(error);
3178
- };
3179
- const checkCallback = () => {
3180
- if (vi.isFakeTimers())
3181
- vi.advanceTimersByTime(interval);
3182
- if (promiseStatus === "pending")
3183
- return;
3184
- try {
3185
- const result = callback();
3186
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
3187
- const thenable = result;
3188
- promiseStatus = "pending";
3189
- thenable.then(
3190
- (resolvedValue) => {
3191
- promiseStatus = "resolved";
3192
- onResolve(resolvedValue);
3193
- },
3194
- (rejectedValue) => {
3195
- promiseStatus = "rejected";
3196
- lastError = rejectedValue;
3197
- }
3198
- );
3199
- } else {
3200
- onResolve(result);
3201
- return true;
3202
- }
3203
- } catch (error) {
3204
- lastError = error;
3205
- }
3206
- };
3207
- if (checkCallback() === true)
3208
- return;
3209
- timeoutId = setTimeout(handleTimeout, timeout);
3210
- intervalId = setInterval(checkCallback, interval);
3211
- });
3212
- }
3213
- function waitUntil(callback, options = {}) {
3214
- const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
3215
- const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
3216
- const STACK_TRACE_ERROR = new Error("STACK_TRACE_ERROR");
3217
- return new Promise((resolve, reject) => {
3218
- let promiseStatus = "idle";
3219
- let timeoutId;
3220
- let intervalId;
3221
- const onReject = (error) => {
3222
- if (!error)
3223
- error = copyStackTrace(new Error("Timed out in waitUntil!"), STACK_TRACE_ERROR);
3224
- reject(error);
3225
- };
3226
- const onResolve = (result) => {
3227
- if (!result)
3228
- return;
3229
- if (timeoutId)
3230
- clearTimeout(timeoutId);
3231
- if (intervalId)
3232
- clearInterval(intervalId);
3233
- resolve(result);
3234
- return true;
3235
- };
3236
- const checkCallback = () => {
3237
- if (vi.isFakeTimers())
3238
- vi.advanceTimersByTime(interval);
3239
- if (promiseStatus === "pending")
3240
- return;
3241
- try {
3242
- const result = callback();
3243
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
3244
- const thenable = result;
3245
- promiseStatus = "pending";
3246
- thenable.then(
3247
- (resolvedValue) => {
3248
- promiseStatus = "resolved";
3249
- onResolve(resolvedValue);
3250
- },
3251
- (rejectedValue) => {
3252
- promiseStatus = "rejected";
3253
- onReject(rejectedValue);
3254
- }
3255
- );
3256
- } else {
3257
- return onResolve(result);
3258
- }
3259
- } catch (error) {
3260
- onReject(error);
3261
- }
3262
- };
3263
- if (checkCallback() === true)
3264
- return;
3265
- timeoutId = setTimeout(onReject, timeout);
3266
- intervalId = setInterval(checkCallback, interval);
3267
- });
3268
- }
3269
-
3270
- function createVitest() {
3271
- const _mocker = typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : new Proxy({}, {
3272
- get(_, name) {
3273
- throw new Error(
3274
- `Vitest mocker was not initialized in this environment. vi.${String(name)}() is forbidden.`
3275
- );
3276
- }
3277
- });
3278
- let _mockedDate = null;
3279
- let _config = null;
3280
- const workerState = getWorkerState();
3281
- if (!workerState) {
3282
- const errorMsg = 'Vitest failed to access its internal state.\n\nOne of the following is possible:\n- "vitest" is imported directly without running "vitest" command\n- "vitest" is imported inside "globalSetup" (to fix this, use "setupFiles" instead, because "globalSetup" runs in a different context)\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n';
3283
- throw new Error(errorMsg);
3284
- }
3285
- const _timers = new FakeTimers({
3286
- global: globalThis,
3287
- config: workerState.config.fakeTimers
3288
- });
3289
- const _stubsGlobal = /* @__PURE__ */ new Map();
3290
- const _stubsEnv = /* @__PURE__ */ new Map();
3291
- const getImporter = () => {
3292
- const stackTrace = createSimpleStackTrace({ stackTraceLimit: 4 });
3293
- const importerStack = stackTrace.split("\n")[4];
3294
- const stack = parseSingleStack(importerStack);
3295
- return (stack == null ? void 0 : stack.file) || "";
3296
- };
3297
- const utils = {
3298
- useFakeTimers(config) {
3299
- var _a, _b, _c, _d;
3300
- const workerState2 = getWorkerState();
3301
- if (workerState2.isChildProcess) {
3302
- if (((_a = config == null ? void 0 : config.toFake) == null ? void 0 : _a.includes("nextTick")) || ((_d = (_c = (_b = workerState2.config) == null ? void 0 : _b.fakeTimers) == null ? void 0 : _c.toFake) == null ? void 0 : _d.includes("nextTick"))) {
3303
- throw new Error(
3304
- 'vi.useFakeTimers({ toFake: ["nextTick"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.'
3305
- );
3306
- }
3307
- }
3308
- if (config)
3309
- _timers.configure({ ...workerState2.config.fakeTimers, ...config });
3310
- else
3311
- _timers.configure(workerState2.config.fakeTimers);
3312
- _timers.useFakeTimers();
3313
- return utils;
3314
- },
3315
- isFakeTimers() {
3316
- return _timers.isFakeTimers();
3317
- },
3318
- useRealTimers() {
3319
- _timers.useRealTimers();
3320
- _mockedDate = null;
3321
- return utils;
3322
- },
3323
- runOnlyPendingTimers() {
3324
- _timers.runOnlyPendingTimers();
3325
- return utils;
3326
- },
3327
- async runOnlyPendingTimersAsync() {
3328
- await _timers.runOnlyPendingTimersAsync();
3329
- return utils;
3330
- },
3331
- runAllTimers() {
3332
- _timers.runAllTimers();
3333
- return utils;
3334
- },
3335
- async runAllTimersAsync() {
3336
- await _timers.runAllTimersAsync();
3337
- return utils;
3338
- },
3339
- runAllTicks() {
3340
- _timers.runAllTicks();
3341
- return utils;
3342
- },
3343
- advanceTimersByTime(ms) {
3344
- _timers.advanceTimersByTime(ms);
3345
- return utils;
3346
- },
3347
- async advanceTimersByTimeAsync(ms) {
3348
- await _timers.advanceTimersByTimeAsync(ms);
3349
- return utils;
3350
- },
3351
- advanceTimersToNextTimer() {
3352
- _timers.advanceTimersToNextTimer();
3353
- return utils;
3354
- },
3355
- async advanceTimersToNextTimerAsync() {
3356
- await _timers.advanceTimersToNextTimerAsync();
3357
- return utils;
3358
- },
3359
- getTimerCount() {
3360
- return _timers.getTimerCount();
3361
- },
3362
- setSystemTime(time) {
3363
- const date = time instanceof Date ? time : new Date(time);
3364
- _mockedDate = date;
3365
- _timers.setSystemTime(date);
3366
- return utils;
3367
- },
3368
- getMockedSystemTime() {
3369
- return _mockedDate;
3370
- },
3371
- getRealSystemTime() {
3372
- return _timers.getRealSystemTime();
3373
- },
3374
- clearAllTimers() {
3375
- _timers.clearAllTimers();
3376
- return utils;
3377
- },
3378
- // mocks
3379
- spyOn,
3380
- fn,
3381
- waitFor,
3382
- waitUntil,
3383
- hoisted(factory) {
3384
- assertTypes(factory, '"vi.hoisted" factory', ["function"]);
3385
- return factory();
3386
- },
3387
- mock(path, factory) {
3388
- const importer = getImporter();
3389
- _mocker.queueMock(
3390
- path,
3391
- importer,
3392
- factory ? () => factory(() => _mocker.importActual(path, importer)) : void 0
3393
- );
3394
- },
3395
- unmock(path) {
3396
- _mocker.queueUnmock(path, getImporter());
3397
- },
3398
- doMock(path, factory) {
3399
- _mocker.queueMock(path, getImporter(), factory);
3400
- },
3401
- doUnmock(path) {
3402
- _mocker.queueUnmock(path, getImporter());
3403
- },
3404
- async importActual(path) {
3405
- return _mocker.importActual(path, getImporter());
3406
- },
3407
- async importMock(path) {
3408
- return _mocker.importMock(path, getImporter());
3409
- },
3410
- mocked(item, _options = {}) {
3411
- return item;
3412
- },
3413
- isMockFunction(fn2) {
3414
- return isMockFunction(fn2);
3415
- },
3416
- clearAllMocks() {
3417
- spies.forEach((spy) => spy.mockClear());
3418
- return utils;
3419
- },
3420
- resetAllMocks() {
3421
- spies.forEach((spy) => spy.mockReset());
3422
- return utils;
3423
- },
3424
- restoreAllMocks() {
3425
- spies.forEach((spy) => spy.mockRestore());
3426
- return utils;
3427
- },
3428
- stubGlobal(name, value) {
3429
- if (!_stubsGlobal.has(name))
3430
- _stubsGlobal.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
3431
- Object.defineProperty(globalThis, name, {
3432
- value,
3433
- writable: true,
3434
- configurable: true,
3435
- enumerable: true
3436
- });
3437
- return utils;
3438
- },
3439
- stubEnv(name, value) {
3440
- if (!_stubsEnv.has(name))
3441
- _stubsEnv.set(name, process.env[name]);
3442
- process.env[name] = value;
3443
- return utils;
3444
- },
3445
- unstubAllGlobals() {
3446
- _stubsGlobal.forEach((original, name) => {
3447
- if (!original)
3448
- Reflect.deleteProperty(globalThis, name);
3449
- else
3450
- Object.defineProperty(globalThis, name, original);
3451
- });
3452
- _stubsGlobal.clear();
3453
- return utils;
3454
- },
3455
- unstubAllEnvs() {
3456
- _stubsEnv.forEach((original, name) => {
3457
- if (original === void 0)
3458
- delete process.env[name];
3459
- else
3460
- process.env[name] = original;
3461
- });
3462
- _stubsEnv.clear();
3463
- return utils;
3464
- },
3465
- resetModules() {
3466
- const state = getWorkerState();
3467
- resetModules(state.moduleCache);
3468
- return utils;
3469
- },
3470
- async dynamicImportSettled() {
3471
- return waitForImportsToResolve();
3472
- },
3473
- setConfig(config) {
3474
- const state = getWorkerState();
3475
- if (!_config)
3476
- _config = { ...state.config };
3477
- Object.assign(state.config, config);
3478
- },
3479
- resetConfig() {
3480
- if (_config) {
3481
- const state = getWorkerState();
3482
- Object.assign(state.config, _config);
3483
- }
3484
- }
3485
- };
3486
- return utils;
3487
- }
3488
- const vitest = createVitest();
3489
- const vi = vitest;
3490
-
3491
- export { globalExpect as a, vitest as b, createExpect as c, getSnapshotClient as g, resetModules as r, vi as v };