vitest 0.0.106 → 0.0.110

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.
@@ -0,0 +1,1018 @@
1
+ import { n as nanoid, a as spyOn, f as fn, s as spies } from './jest-mock-a57b745c.js';
2
+ import { n as noop } from './utils-d97bd6d9.js';
3
+ import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './_commonjsHelpers-c9e3b764.js';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __defProps = Object.defineProperties;
7
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ function createChainable(keys, fn) {
25
+ function create(obj) {
26
+ const chain2 = function(...args) {
27
+ return fn.apply(obj, args);
28
+ };
29
+ for (const key of keys) {
30
+ Object.defineProperty(chain2, key, {
31
+ get() {
32
+ return create(__spreadProps(__spreadValues({}, obj), { [key]: true }));
33
+ }
34
+ });
35
+ }
36
+ return chain2;
37
+ }
38
+ const chain = create({});
39
+ chain.fn = fn;
40
+ return chain;
41
+ }
42
+
43
+ const context = {
44
+ tasks: [],
45
+ currentSuite: null
46
+ };
47
+ function collectTask(task) {
48
+ var _a;
49
+ (_a = context.currentSuite) == null ? void 0 : _a.tasks.push(task);
50
+ }
51
+ async function runWithSuite(suite, fn) {
52
+ const prev = context.currentSuite;
53
+ context.currentSuite = suite;
54
+ await fn();
55
+ context.currentSuite = prev;
56
+ }
57
+ function getDefaultTestTimeout() {
58
+ return process.__vitest_worker__.config.testTimeout;
59
+ }
60
+ function getDefaultHookTimeout() {
61
+ return process.__vitest_worker__.config.hookTimeout;
62
+ }
63
+ function withTimeout(fn, _timeout) {
64
+ const timeout = _timeout ?? getDefaultTestTimeout();
65
+ if (timeout <= 0 || timeout === Infinity)
66
+ return fn;
67
+ return (...args) => {
68
+ return Promise.race([fn(...args), new Promise((resolve, reject) => {
69
+ const timer = setTimeout(() => {
70
+ clearTimeout(timer);
71
+ reject(new Error(`Test timed out in ${timeout}ms.`));
72
+ }, timeout);
73
+ timer.unref();
74
+ })]);
75
+ };
76
+ }
77
+ function ensureAsyncTest(fn) {
78
+ if (!fn.length)
79
+ return fn;
80
+ return () => new Promise((resolve, reject) => {
81
+ const done = (...args) => args[0] ? reject(args[0]) : resolve();
82
+ fn(done);
83
+ });
84
+ }
85
+ function normalizeTest(fn, timeout) {
86
+ return withTimeout(ensureAsyncTest(fn), timeout);
87
+ }
88
+
89
+ const fnMap = /* @__PURE__ */ new WeakMap();
90
+ const hooksMap = /* @__PURE__ */ new WeakMap();
91
+ function setFn(key, fn) {
92
+ fnMap.set(key, fn);
93
+ }
94
+ function getFn(key) {
95
+ return fnMap.get(key);
96
+ }
97
+ function setHooks(key, hooks) {
98
+ hooksMap.set(key, hooks);
99
+ }
100
+ function getHooks(key) {
101
+ return hooksMap.get(key);
102
+ }
103
+
104
+ const suite = createSuite();
105
+ const test = createChainable(["concurrent", "skip", "only", "todo", "fails"], function(name, fn, timeout) {
106
+ getCurrentSuite().test.fn.call(this, name, fn, timeout);
107
+ });
108
+ const describe = suite;
109
+ const it = test;
110
+ const defaultSuite = suite("");
111
+ function clearContext() {
112
+ context.tasks.length = 0;
113
+ defaultSuite.clear();
114
+ context.currentSuite = defaultSuite;
115
+ }
116
+ function getCurrentSuite() {
117
+ return context.currentSuite || defaultSuite;
118
+ }
119
+ function createSuiteHooks() {
120
+ return {
121
+ beforeAll: [],
122
+ afterAll: [],
123
+ beforeEach: [],
124
+ afterEach: []
125
+ };
126
+ }
127
+ function createSuiteCollector(name, factory = () => {
128
+ }, mode, suiteComputeMode) {
129
+ const tasks = [];
130
+ const factoryQueue = [];
131
+ let suite2;
132
+ initSuite();
133
+ const test2 = createChainable(["concurrent", "skip", "only", "todo", "fails"], function(name2, fn, timeout) {
134
+ const mode2 = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
135
+ const computeMode = this.concurrent ? "concurrent" : void 0;
136
+ const test3 = {
137
+ id: nanoid(),
138
+ type: "test",
139
+ name: name2,
140
+ mode: mode2,
141
+ computeMode: computeMode ?? (suiteComputeMode ?? "serial"),
142
+ suite: void 0,
143
+ fails: this.fails
144
+ };
145
+ setFn(test3, normalizeTest(fn || noop, timeout));
146
+ tasks.push(test3);
147
+ });
148
+ const collector = {
149
+ type: "collector",
150
+ name,
151
+ mode,
152
+ test: test2,
153
+ tasks,
154
+ collect,
155
+ clear,
156
+ on: addHook
157
+ };
158
+ function addHook(name2, ...fn) {
159
+ getHooks(suite2)[name2].push(...fn);
160
+ }
161
+ function initSuite() {
162
+ suite2 = {
163
+ id: nanoid(),
164
+ type: "suite",
165
+ computeMode: "serial",
166
+ name,
167
+ mode,
168
+ tasks: []
169
+ };
170
+ setHooks(suite2, createSuiteHooks());
171
+ }
172
+ function clear() {
173
+ tasks.length = 0;
174
+ factoryQueue.length = 0;
175
+ initSuite();
176
+ }
177
+ async function collect(file) {
178
+ factoryQueue.length = 0;
179
+ if (factory)
180
+ await runWithSuite(collector, () => factory(test2));
181
+ const allChildren = await Promise.all([...factoryQueue, ...tasks].map((i) => i.type === "collector" ? i.collect(file) : i));
182
+ suite2.file = file;
183
+ suite2.tasks = allChildren;
184
+ allChildren.forEach((task) => {
185
+ task.suite = suite2;
186
+ if (file)
187
+ task.file = file;
188
+ });
189
+ return suite2;
190
+ }
191
+ collectTask(collector);
192
+ return collector;
193
+ }
194
+ function createSuite() {
195
+ return createChainable(["concurrent", "skip", "only", "todo"], function(name, factory) {
196
+ const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
197
+ const computeMode = this.concurrent ? "concurrent" : void 0;
198
+ return createSuiteCollector(name, factory, mode, computeMode);
199
+ });
200
+ }
201
+
202
+ const isObject = (val) => toString.call(val) === "[object Object]";
203
+ function equals(a, b, customTesters, strictCheck) {
204
+ customTesters = customTesters || [];
205
+ return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey);
206
+ }
207
+ function isAsymmetric(obj) {
208
+ return !!obj && isA("Function", obj.asymmetricMatch);
209
+ }
210
+ function hasAsymmetric(obj, seen = /* @__PURE__ */ new Set()) {
211
+ if (seen.has(obj))
212
+ return false;
213
+ seen.add(obj);
214
+ if (isAsymmetric(obj))
215
+ return true;
216
+ if (Array.isArray(obj))
217
+ return obj.some((i) => hasAsymmetric(i, seen));
218
+ if (obj instanceof Set)
219
+ return Array.from(obj).some((i) => hasAsymmetric(i, seen));
220
+ if (isObject(obj))
221
+ return Object.values(obj).some((v) => hasAsymmetric(v, seen));
222
+ return false;
223
+ }
224
+ function asymmetricMatch(a, b) {
225
+ const asymmetricA = isAsymmetric(a);
226
+ const asymmetricB = isAsymmetric(b);
227
+ if (asymmetricA && asymmetricB)
228
+ return void 0;
229
+ if (asymmetricA)
230
+ return a.asymmetricMatch(b);
231
+ if (asymmetricB)
232
+ return b.asymmetricMatch(a);
233
+ }
234
+ function eq(a, b, aStack, bStack, customTesters, hasKey2) {
235
+ let result = true;
236
+ const asymmetricResult = asymmetricMatch(a, b);
237
+ if (asymmetricResult !== void 0)
238
+ return asymmetricResult;
239
+ for (let i = 0; i < customTesters.length; i++) {
240
+ const customTesterResult = customTesters[i](a, b);
241
+ if (customTesterResult !== void 0)
242
+ return customTesterResult;
243
+ }
244
+ if (a instanceof Error && b instanceof Error)
245
+ return a.message === b.message;
246
+ if (Object.is(a, b))
247
+ return true;
248
+ if (a === null || b === null)
249
+ return a === b;
250
+ const className = Object.prototype.toString.call(a);
251
+ if (className !== Object.prototype.toString.call(b))
252
+ return false;
253
+ switch (className) {
254
+ case "[object Boolean]":
255
+ case "[object String]":
256
+ case "[object Number]":
257
+ if (typeof a !== typeof b) {
258
+ return false;
259
+ } else if (typeof a !== "object" && typeof b !== "object") {
260
+ return Object.is(a, b);
261
+ } else {
262
+ return Object.is(a.valueOf(), b.valueOf());
263
+ }
264
+ case "[object Date]":
265
+ return +a === +b;
266
+ case "[object RegExp]":
267
+ return a.source === b.source && a.flags === b.flags;
268
+ }
269
+ if (typeof a !== "object" || typeof b !== "object")
270
+ return false;
271
+ if (isDomNode(a) && isDomNode(b))
272
+ return a.isEqualNode(b);
273
+ let length = aStack.length;
274
+ while (length--) {
275
+ if (aStack[length] === a)
276
+ return bStack[length] === b;
277
+ else if (bStack[length] === b)
278
+ return false;
279
+ }
280
+ aStack.push(a);
281
+ bStack.push(b);
282
+ if (className === "[object Array]" && a.length !== b.length)
283
+ return false;
284
+ const aKeys = keys(a, hasKey2);
285
+ let key;
286
+ let size = aKeys.length;
287
+ if (keys(b, hasKey2).length !== size)
288
+ return false;
289
+ while (size--) {
290
+ key = aKeys[size];
291
+ result = hasKey2(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey2);
292
+ if (!result)
293
+ return false;
294
+ }
295
+ aStack.pop();
296
+ bStack.pop();
297
+ return result;
298
+ }
299
+ function keys(obj, hasKey2) {
300
+ const keys2 = [];
301
+ for (const key in obj) {
302
+ if (hasKey2(obj, key))
303
+ keys2.push(key);
304
+ }
305
+ return keys2.concat(Object.getOwnPropertySymbols(obj).filter((symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable));
306
+ }
307
+ function hasDefinedKey(obj, key) {
308
+ return hasKey(obj, key) && obj[key] !== void 0;
309
+ }
310
+ function hasKey(obj, key) {
311
+ return Object.prototype.hasOwnProperty.call(obj, key);
312
+ }
313
+ function isA(typeName, value) {
314
+ return Object.prototype.toString.apply(value) === `[object ${typeName}]`;
315
+ }
316
+ function isDomNode(obj) {
317
+ return obj !== null && typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string" && typeof obj.isEqualNode === "function";
318
+ }
319
+ const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@";
320
+ const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@";
321
+ const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@";
322
+ function isImmutableUnorderedKeyed(maybeKeyed) {
323
+ return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL] && !maybeKeyed[IS_ORDERED_SENTINEL]);
324
+ }
325
+ function isImmutableUnorderedSet(maybeSet) {
326
+ return !!(maybeSet && maybeSet[IS_SET_SENTINEL] && !maybeSet[IS_ORDERED_SENTINEL]);
327
+ }
328
+ const IteratorSymbol = Symbol.iterator;
329
+ const hasIterator = (object) => !!(object != null && object[IteratorSymbol]);
330
+ const iterableEquality = (a, b, aStack = [], bStack = []) => {
331
+ if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b))
332
+ return void 0;
333
+ if (a.constructor !== b.constructor)
334
+ return false;
335
+ let length = aStack.length;
336
+ while (length--) {
337
+ if (aStack[length] === a)
338
+ return bStack[length] === b;
339
+ }
340
+ aStack.push(a);
341
+ bStack.push(b);
342
+ const iterableEqualityWithStack = (a2, b2) => iterableEquality(a2, b2, [...aStack], [...bStack]);
343
+ if (a.size !== void 0) {
344
+ if (a.size !== b.size) {
345
+ return false;
346
+ } else if (isA("Set", a) || isImmutableUnorderedSet(a)) {
347
+ let allFound = true;
348
+ for (const aValue of a) {
349
+ if (!b.has(aValue)) {
350
+ let has = false;
351
+ for (const bValue of b) {
352
+ const isEqual = equals(aValue, bValue, [iterableEqualityWithStack]);
353
+ if (isEqual === true)
354
+ has = true;
355
+ }
356
+ if (has === false) {
357
+ allFound = false;
358
+ break;
359
+ }
360
+ }
361
+ }
362
+ aStack.pop();
363
+ bStack.pop();
364
+ return allFound;
365
+ } else if (isA("Map", a) || isImmutableUnorderedKeyed(a)) {
366
+ let allFound = true;
367
+ for (const aEntry of a) {
368
+ if (!b.has(aEntry[0]) || !equals(aEntry[1], b.get(aEntry[0]), [iterableEqualityWithStack])) {
369
+ let has = false;
370
+ for (const bEntry of b) {
371
+ const matchedKey = equals(aEntry[0], bEntry[0], [
372
+ iterableEqualityWithStack
373
+ ]);
374
+ let matchedValue = false;
375
+ if (matchedKey === true) {
376
+ matchedValue = equals(aEntry[1], bEntry[1], [
377
+ iterableEqualityWithStack
378
+ ]);
379
+ }
380
+ if (matchedValue === true)
381
+ has = true;
382
+ }
383
+ if (has === false) {
384
+ allFound = false;
385
+ break;
386
+ }
387
+ }
388
+ }
389
+ aStack.pop();
390
+ bStack.pop();
391
+ return allFound;
392
+ }
393
+ }
394
+ const bIterator = b[IteratorSymbol]();
395
+ for (const aValue of a) {
396
+ const nextB = bIterator.next();
397
+ if (nextB.done || !equals(aValue, nextB.value, [iterableEqualityWithStack]))
398
+ return false;
399
+ }
400
+ if (!bIterator.next().done)
401
+ return false;
402
+ aStack.pop();
403
+ bStack.pop();
404
+ return true;
405
+ };
406
+ const hasPropertyInObject = (object, key) => {
407
+ const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype;
408
+ if (shouldTerminate)
409
+ return false;
410
+ return Object.prototype.hasOwnProperty.call(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key);
411
+ };
412
+ const isObjectWithKeys = (a) => isObject(a) && !(a instanceof Error) && !(a instanceof Array) && !(a instanceof Date);
413
+ const subsetEquality = (object, subset) => {
414
+ const subsetEqualityWithContext = (seenReferences = /* @__PURE__ */ new WeakMap()) => (object2, subset2) => {
415
+ if (!isObjectWithKeys(subset2))
416
+ return void 0;
417
+ return Object.keys(subset2).every((key) => {
418
+ if (isObjectWithKeys(subset2[key])) {
419
+ if (seenReferences.has(subset2[key]))
420
+ return equals(object2[key], subset2[key], [iterableEquality]);
421
+ seenReferences.set(subset2[key], true);
422
+ }
423
+ const result = object2 != null && hasPropertyInObject(object2, key) && equals(object2[key], subset2[key], [
424
+ iterableEquality,
425
+ subsetEqualityWithContext(seenReferences)
426
+ ]);
427
+ seenReferences.delete(subset2[key]);
428
+ return result;
429
+ });
430
+ };
431
+ return subsetEqualityWithContext()(object, subset);
432
+ };
433
+
434
+ const MATCHERS_OBJECT = Symbol.for("matchers-object");
435
+ if (!Object.prototype.hasOwnProperty.call(global, MATCHERS_OBJECT)) {
436
+ const defaultState = {
437
+ assertionCalls: 0,
438
+ expectedAssertionsNumber: null,
439
+ expectedAssertionsNumberError: null
440
+ };
441
+ Object.defineProperty(global, MATCHERS_OBJECT, {
442
+ value: {
443
+ state: defaultState
444
+ }
445
+ });
446
+ }
447
+ const getState = () => global[MATCHERS_OBJECT].state;
448
+ const setState = (state) => {
449
+ Object.assign(global[MATCHERS_OBJECT].state, state);
450
+ };
451
+ const JestChaiExpect = (chai, utils) => {
452
+ function def(name, fn) {
453
+ const addMethod = (n) => {
454
+ utils.addMethod(chai.Assertion.prototype, n, fn);
455
+ };
456
+ if (Array.isArray(name))
457
+ name.forEach((n) => addMethod(n));
458
+ else
459
+ addMethod(name);
460
+ }
461
+ const chaiEqual = chai.Assertion.prototype.equal;
462
+ def("chaiEqual", function(...args) {
463
+ return chaiEqual.apply(this, args);
464
+ });
465
+ utils.overwriteMethod(chai.Assertion.prototype, "equal", (_super) => {
466
+ return function(...args) {
467
+ const expected = args[0];
468
+ const actual = utils.flag(this, "object");
469
+ if (hasAsymmetric(expected)) {
470
+ this.assert(equals(actual, expected, void 0, true), "not match with #{act}", "should not match with #{act}", actual, expected);
471
+ } else {
472
+ _super.apply(this, args);
473
+ }
474
+ };
475
+ });
476
+ utils.overwriteMethod(chai.Assertion.prototype, "eql", (_super) => {
477
+ return function(...args) {
478
+ const expected = args[0];
479
+ const actual = utils.flag(this, "object");
480
+ if (hasAsymmetric(expected)) {
481
+ this.assert(equals(actual, expected), "not match with #{exp}", "should not match with #{exp}", actual, expected);
482
+ } else {
483
+ _super.apply(this, args);
484
+ }
485
+ };
486
+ });
487
+ def("toEqual", function(expected) {
488
+ return this.eql(expected);
489
+ });
490
+ def("toStrictEqual", function(expected) {
491
+ return this.chaiEqual(expected);
492
+ });
493
+ def("toBe", function(expected) {
494
+ return this.equal(expected);
495
+ });
496
+ def("toMatchObject", function(expected) {
497
+ return this.containSubset(expected);
498
+ });
499
+ def("toMatch", function(expected) {
500
+ if (typeof expected === "string")
501
+ return this.include(expected);
502
+ else
503
+ return this.match(expected);
504
+ });
505
+ def("toContain", function(item) {
506
+ return this.contain(item);
507
+ });
508
+ def("toContainEqual", function(expected) {
509
+ const obj = utils.flag(this, "object");
510
+ const index = Array.from(obj).findIndex((item) => {
511
+ try {
512
+ chai.assert.deepEqual(item, expected);
513
+ } catch {
514
+ return false;
515
+ }
516
+ return true;
517
+ });
518
+ this.assert(index !== -1, "expected #{this} to deep equally contain #{exp}", "expected #{this} to not deep equally contain #{exp}", expected);
519
+ });
520
+ def("toBeTruthy", function() {
521
+ const obj = utils.flag(this, "object");
522
+ this.assert(Boolean(obj), "expected #{this} to be truthy", "expected #{this} to not be truthy", obj);
523
+ });
524
+ def("toBeFalsy", function() {
525
+ const obj = utils.flag(this, "object");
526
+ this.assert(!obj, "expected #{this} to be falsy", "expected #{this} to not be falsy", obj);
527
+ });
528
+ def("toBeGreaterThan", function(expected) {
529
+ return this.to.greaterThan(expected);
530
+ });
531
+ def("toBeGreaterThanOrEqual", function(expected) {
532
+ return this.to.greaterThanOrEqual(expected);
533
+ });
534
+ def("toBeLessThan", function(expected) {
535
+ return this.to.lessThan(expected);
536
+ });
537
+ def("toBeLessThanOrEqual", function(expected) {
538
+ return this.to.lessThanOrEqual(expected);
539
+ });
540
+ def("toBeNaN", function() {
541
+ return this.be.NaN;
542
+ });
543
+ def("toBeUndefined", function() {
544
+ return this.be.undefined;
545
+ });
546
+ def("toBeNull", function() {
547
+ return this.be.null;
548
+ });
549
+ def("toBeDefined", function() {
550
+ return this.not.be.undefined;
551
+ });
552
+ def("toBeInstanceOf", function(obj) {
553
+ return this.instanceOf(obj);
554
+ });
555
+ def("toHaveLength", function(length) {
556
+ return this.have.length(length);
557
+ });
558
+ def("toHaveProperty", function(...args) {
559
+ return this.have.deep.nested.property(...args);
560
+ });
561
+ def("toBeCloseTo", function(number, numDigits = 2) {
562
+ utils.expectTypes(this, ["number"]);
563
+ return this.closeTo(number, numDigits);
564
+ });
565
+ function isSpy(putativeSpy) {
566
+ return typeof putativeSpy === "function" && "__isSpy" in putativeSpy && putativeSpy.__isSpy;
567
+ }
568
+ const assertIsMock = (assertion) => {
569
+ if (!isSpy(assertion._obj))
570
+ throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`);
571
+ };
572
+ const getSpy = (assertion) => {
573
+ assertIsMock(assertion);
574
+ return assertion._obj;
575
+ };
576
+ def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) {
577
+ const spy = getSpy(this);
578
+ return this.assert(spy.callCount === number, "expected spy to be called #{exp} times", "expected spy to not be called #{exp} times", number, spy.callCount);
579
+ });
580
+ def("toHaveBeenCalledOnce", function() {
581
+ const spy = getSpy(this);
582
+ return this.assert(spy.callCount === 1, "expected spy to be called once", "expected spy to not be called once", 1, spy.callCount);
583
+ });
584
+ def(["toHaveBeenCalled", "toBeCalled"], function() {
585
+ const spy = getSpy(this);
586
+ return this.assert(spy.called, "expected spy to be called at least once", "expected spy to not be called at all", true, spy.called);
587
+ });
588
+ def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) {
589
+ const spy = getSpy(this);
590
+ const pass = spy.calls.some((callArg) => equals(callArg, args));
591
+ return this.assert(pass, "expected spy to be called with arguments: #{exp}", "expected spy to not be called with arguments: #{exp}", args, spy.calls);
592
+ });
593
+ const ordinalOf = (i) => {
594
+ const j = i % 10;
595
+ const k = i % 100;
596
+ if (j === 1 && k !== 11)
597
+ return `${i}st`;
598
+ if (j === 2 && k !== 12)
599
+ return `${i}nd`;
600
+ if (j === 3 && k !== 13)
601
+ return `${i}rd`;
602
+ return `${i}th`;
603
+ };
604
+ def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) {
605
+ const spy = getSpy(this);
606
+ const nthCall = spy.calls[times - 1];
607
+ this.assert(equals(nthCall, args), `expected ${ordinalOf(times)} spy call to have been called with #{exp}`, `expected ${ordinalOf(times)} spy call to not have been called with #{exp}`, args, nthCall);
608
+ });
609
+ def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) {
610
+ const spy = getSpy(this);
611
+ const lastCall = spy.calls[spy.calls.length - 1];
612
+ this.assert(equals(lastCall, args), "expected last spy call to have been called with #{exp}", "expected last spy call to not have been called with #{exp}", args, lastCall);
613
+ });
614
+ def(["toThrow", "toThrowError"], function(expected) {
615
+ const negate = utils.flag(this, "negate");
616
+ if (negate)
617
+ this.not.to.throw(expected);
618
+ else
619
+ this.to.throw(expected);
620
+ });
621
+ def(["toHaveReturned", "toReturn"], function() {
622
+ const spy = getSpy(this);
623
+ const calledAndNotThrew = spy.called && !spy.results.some(([type]) => type === "error");
624
+ this.assert(calledAndNotThrew, "expected spy to be successfully called at least once", "expected spy to not be successfully called", calledAndNotThrew, !calledAndNotThrew);
625
+ });
626
+ def(["toHaveReturnedTimes", "toReturnTimes"], function(times) {
627
+ const spy = getSpy(this);
628
+ const successfullReturns = spy.results.reduce((success, [type]) => type === "error" ? success : ++success, 0);
629
+ this.assert(successfullReturns === times, `expected spy to be successfully called ${times} times`, `expected spy to not be successfully called ${times} times`, `expected number of returns: ${times}`, `received number of returns: ${successfullReturns}`);
630
+ });
631
+ def(["toHaveReturnedWith", "toReturnWith"], function(value) {
632
+ const spy = getSpy(this);
633
+ const pass = spy.results.some(([type, result]) => type === "ok" && equals(value, result));
634
+ this.assert(pass, "expected spy to be successfully called with #{exp}", "expected spy to not be successfully called with #{exp}", value);
635
+ });
636
+ def(["toHaveLastReturnedWith", "lastReturnedWith"], function(value) {
637
+ const spy = getSpy(this);
638
+ const lastResult = spy.returns[spy.returns.length - 1];
639
+ const pass = equals(lastResult, value);
640
+ this.assert(pass, "expected last spy call to return #{exp}", "expected last spy call to not return #{exp}", value, lastResult);
641
+ });
642
+ def(["toHaveNthReturnedWith", "nthReturnedWith"], function(nthCall, value) {
643
+ const spy = getSpy(this);
644
+ const isNot = utils.flag(this, "negate");
645
+ const [callType, callResult] = spy.results[nthCall - 1];
646
+ const ordinalCall = `${ordinalOf(nthCall)} call`;
647
+ if (!isNot && callType === "error")
648
+ chai.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`);
649
+ const nthCallReturn = equals(callResult, value);
650
+ this.assert(nthCallReturn, `expected ${ordinalCall} spy call to return #{exp}`, `expected ${ordinalCall} spy call to not return #{exp}`, value, callResult);
651
+ });
652
+ utils.addMethod(chai.expect, "assertions", function assertions(expected) {
653
+ const error = new Error(`expected number of assertions to be ${expected}, but got ${getState().assertionCalls}`);
654
+ if (Error.captureStackTrace)
655
+ Error.captureStackTrace(error, assertions);
656
+ setState({
657
+ expectedAssertionsNumber: expected,
658
+ expectedAssertionsNumberError: error
659
+ });
660
+ });
661
+ };
662
+
663
+ var mockdate$1 = {exports: {}};
664
+
665
+ (function (module, exports) {
666
+ (function (global, factory) {
667
+ factory(exports) ;
668
+ }(commonjsGlobal, (function (exports) {
669
+ /*! *****************************************************************************
670
+ Copyright (c) Microsoft Corporation.
671
+
672
+ Permission to use, copy, modify, and/or distribute this software for any
673
+ purpose with or without fee is hereby granted.
674
+
675
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
676
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
677
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
678
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
679
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
680
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
681
+ PERFORMANCE OF THIS SOFTWARE.
682
+ ***************************************************************************** */
683
+ /* global Reflect, Promise */
684
+
685
+ var extendStatics = function(d, b) {
686
+ extendStatics = Object.setPrototypeOf ||
687
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
688
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
689
+ return extendStatics(d, b);
690
+ };
691
+
692
+ function __extends(d, b) {
693
+ if (typeof b !== "function" && b !== null)
694
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
695
+ extendStatics(d, b);
696
+ function __() { this.constructor = d; }
697
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
698
+ }
699
+
700
+ var RealDate = Date;
701
+ var now = null;
702
+ var MockDate = /** @class */ (function (_super) {
703
+ __extends(Date, _super);
704
+ function Date(y, m, d, h, M, s, ms) {
705
+ _super.call(this) || this;
706
+ var date;
707
+ switch (arguments.length) {
708
+ case 0:
709
+ if (now !== null) {
710
+ date = new RealDate(now.valueOf());
711
+ }
712
+ else {
713
+ date = new RealDate();
714
+ }
715
+ break;
716
+ case 1:
717
+ date = new RealDate(y);
718
+ break;
719
+ default:
720
+ d = typeof d === 'undefined' ? 1 : d;
721
+ h = h || 0;
722
+ M = M || 0;
723
+ s = s || 0;
724
+ ms = ms || 0;
725
+ date = new RealDate(y, m, d, h, M, s, ms);
726
+ break;
727
+ }
728
+ return date;
729
+ }
730
+ return Date;
731
+ }(RealDate));
732
+ MockDate.prototype = RealDate.prototype;
733
+ MockDate.UTC = RealDate.UTC;
734
+ MockDate.now = function () {
735
+ return new MockDate().valueOf();
736
+ };
737
+ MockDate.parse = function (dateString) {
738
+ return RealDate.parse(dateString);
739
+ };
740
+ MockDate.toString = function () {
741
+ return RealDate.toString();
742
+ };
743
+ function set(date) {
744
+ var dateObj = new Date(date.valueOf());
745
+ if (isNaN(dateObj.getTime())) {
746
+ throw new TypeError('mockdate: The time set is an invalid date: ' + date);
747
+ }
748
+ // @ts-ignore
749
+ Date = MockDate;
750
+ now = dateObj.valueOf();
751
+ }
752
+ function reset() {
753
+ Date = RealDate;
754
+ }
755
+ var mockdate = {
756
+ set: set,
757
+ reset: reset,
758
+ };
759
+
760
+ exports.default = mockdate;
761
+ exports.reset = reset;
762
+ exports.set = set;
763
+
764
+ Object.defineProperty(exports, '__esModule', { value: true });
765
+
766
+ })));
767
+ }(mockdate$1, mockdate$1.exports));
768
+
769
+ var mockdate = /*@__PURE__*/getDefaultExportFromCjs(mockdate$1.exports);
770
+
771
+ const originalSetTimeout = global.setTimeout;
772
+ const originalSetInterval = global.setInterval;
773
+ const originalClearTimeout = global.clearTimeout;
774
+ const originalClearInterval = global.clearInterval;
775
+ const MAX_LOOPS = 1e4;
776
+ const assertEvery = (assertions, message) => {
777
+ if (assertions.some((a) => !a))
778
+ throw new Error(message);
779
+ };
780
+ const assertMaxLoop = (times) => {
781
+ if (times >= MAX_LOOPS)
782
+ throw new Error("setTimeout/setInterval called 10 000 times. It's possible it stuck in an infinite loop.");
783
+ };
784
+ const getNodeTimeout = (id) => {
785
+ const timer = {
786
+ ref: () => timer,
787
+ unref: () => timer,
788
+ hasRef: () => true,
789
+ refresh: () => timer,
790
+ [Symbol.toPrimitive]: () => id
791
+ };
792
+ return timer;
793
+ };
794
+ class FakeTimers {
795
+ constructor() {
796
+ this._advancedTime = 0;
797
+ this._nestedTime = {};
798
+ this._scopeId = 0;
799
+ this._isNested = false;
800
+ this._isOnlyPending = false;
801
+ this._spyid = 0;
802
+ this._isMocked = false;
803
+ this._tasksQueue = [];
804
+ this._queueCount = 0;
805
+ }
806
+ useFakeTimers() {
807
+ this._isMocked = true;
808
+ this.reset();
809
+ const spyFactory = (spyType, resultBuilder) => {
810
+ return (cb, ms = 0) => {
811
+ const id = ++this._spyid;
812
+ const nestedTo = Object.entries(this._nestedTime).filter(([key]) => Number(key) <= this._scopeId);
813
+ const nestedMs = nestedTo.reduce((total, [, ms2]) => total + ms2, ms);
814
+ const call = { id, cb, ms, nestedMs, scopeId: this._scopeId };
815
+ const task = { type: spyType, call, nested: this._isNested };
816
+ this.pushTask(task);
817
+ return resultBuilder(id, cb);
818
+ };
819
+ };
820
+ this._setTimeout = spyOn(global, "setTimeout").mockImplementation(spyFactory("timeout" /* Timeout */, getNodeTimeout));
821
+ this._setInterval = spyOn(global, "setInterval").mockImplementation(spyFactory("interval" /* Interval */, getNodeTimeout));
822
+ const clearTimerFactory = (spyType) => (id) => {
823
+ if (id === void 0)
824
+ return;
825
+ const index = this._tasksQueue.findIndex(({ call, type }) => type === spyType && call.id === Number(id));
826
+ if (index !== -1)
827
+ this._tasksQueue.splice(index, 1);
828
+ };
829
+ this._clearTimeout = spyOn(global, "clearTimeout").mockImplementation(clearTimerFactory("timeout" /* Timeout */));
830
+ this._clearInterval = spyOn(global, "clearInterval").mockImplementation(clearTimerFactory("interval" /* Interval */));
831
+ }
832
+ useRealTimers() {
833
+ this._isMocked = false;
834
+ this.reset();
835
+ global.setTimeout = originalSetTimeout;
836
+ global.setInterval = originalSetInterval;
837
+ global.clearTimeout = originalClearTimeout;
838
+ global.clearInterval = originalClearInterval;
839
+ }
840
+ runOnlyPendingTimers() {
841
+ this.assertMocked();
842
+ this._isOnlyPending = true;
843
+ this.runQueue();
844
+ }
845
+ runAllTimers() {
846
+ this.assertMocked();
847
+ this.runQueue();
848
+ }
849
+ advanceTimersByTime(ms) {
850
+ this.assertMocked();
851
+ this._advancedTime += ms;
852
+ this.runQueue();
853
+ }
854
+ advanceTimersToNextTimer() {
855
+ this.assertMocked();
856
+ this.callQueueItem(0);
857
+ }
858
+ getTimerCount() {
859
+ this.assertMocked();
860
+ return this._tasksQueue.length;
861
+ }
862
+ reset() {
863
+ var _a, _b, _c, _d;
864
+ this._advancedTime = 0;
865
+ this._nestedTime = {};
866
+ this._isNested = false;
867
+ this._isOnlyPending = false;
868
+ this._spyid = 0;
869
+ this._queueCount = 0;
870
+ this._tasksQueue = [];
871
+ (_a = this._clearInterval) == null ? void 0 : _a.mockRestore();
872
+ (_b = this._clearTimeout) == null ? void 0 : _b.mockRestore();
873
+ (_c = this._setInterval) == null ? void 0 : _c.mockRestore();
874
+ (_d = this._setTimeout) == null ? void 0 : _d.mockRestore();
875
+ }
876
+ callQueueItem(index) {
877
+ var _a, _b;
878
+ const task = this._tasksQueue[index];
879
+ if (!task)
880
+ return;
881
+ const { call, type } = task;
882
+ this._scopeId = call.id;
883
+ this._isNested = true;
884
+ (_a = this._nestedTime)[_b = call.id] ?? (_a[_b] = 0);
885
+ this._nestedTime[call.id] += call.ms;
886
+ if (type === "timeout") {
887
+ this.removeTask(index);
888
+ } else if (type === "interval") {
889
+ call.nestedMs += call.ms;
890
+ const nestedMs = call.nestedMs;
891
+ const closestTask = this._tasksQueue.findIndex(({ type: type2, call: call2 }) => type2 === "interval" && call2.nestedMs < nestedMs);
892
+ if (closestTask !== -1 && closestTask !== index)
893
+ this.ensureQueueOrder();
894
+ }
895
+ call.cb();
896
+ this._queueCount++;
897
+ }
898
+ runQueue() {
899
+ let index = 0;
900
+ while (this._tasksQueue[index]) {
901
+ assertMaxLoop(this._queueCount);
902
+ const { call, nested } = this._tasksQueue[index];
903
+ if (this._advancedTime && call.nestedMs > this._advancedTime)
904
+ break;
905
+ if (this._isOnlyPending && nested) {
906
+ index++;
907
+ continue;
908
+ }
909
+ this.callQueueItem(index);
910
+ }
911
+ }
912
+ removeTask(index) {
913
+ if (index === 0)
914
+ this._tasksQueue.shift();
915
+ else
916
+ this._tasksQueue.splice(index, 1);
917
+ }
918
+ pushTask(task) {
919
+ this._tasksQueue.push(task);
920
+ this.ensureQueueOrder();
921
+ }
922
+ ensureQueueOrder() {
923
+ this._tasksQueue.sort((t1, t2) => {
924
+ const diff = t1.call.nestedMs - t2.call.nestedMs;
925
+ if (diff === 0) {
926
+ if (t1.type === "immediate" /* Immediate */ && t2.type !== "immediate" /* Immediate */)
927
+ return 1;
928
+ return 0;
929
+ }
930
+ return diff;
931
+ });
932
+ }
933
+ assertMocked() {
934
+ assertEvery([
935
+ this._isMocked,
936
+ this._setTimeout,
937
+ this._setInterval,
938
+ this._clearTimeout,
939
+ this._clearInterval
940
+ ], 'timers are not mocked. try calling "vitest.useFakeTimers()" first');
941
+ }
942
+ }
943
+
944
+ class VitestUtils {
945
+ constructor() {
946
+ this.spyOn = spyOn;
947
+ this.fn = fn;
948
+ this._timers = new FakeTimers();
949
+ this._mockedDate = null;
950
+ }
951
+ useFakeTimers() {
952
+ return this._timers.useFakeTimers();
953
+ }
954
+ useRealTimers() {
955
+ return this._timers.useRealTimers();
956
+ }
957
+ runOnlyPendingTimers() {
958
+ return this._timers.runOnlyPendingTimers();
959
+ }
960
+ runAllTimers() {
961
+ return this._timers.runAllTimers();
962
+ }
963
+ advanceTimersByTime(ms) {
964
+ return this._timers.advanceTimersByTime(ms);
965
+ }
966
+ advanceTimersToNextTimer() {
967
+ return this._timers.advanceTimersToNextTimer();
968
+ }
969
+ getTimerCount() {
970
+ return this._timers.getTimerCount();
971
+ }
972
+ mockCurrentDate(date) {
973
+ this._mockedDate = date;
974
+ mockdate.set(date);
975
+ }
976
+ restoreCurrentDate() {
977
+ this._mockedDate = null;
978
+ mockdate.reset();
979
+ }
980
+ getMockedDate() {
981
+ return this._mockedDate;
982
+ }
983
+ mock(path, factory) {
984
+ }
985
+ unmock(path) {
986
+ }
987
+ async importActual(path) {
988
+ return {};
989
+ }
990
+ async importMock(path) {
991
+ return {};
992
+ }
993
+ mocked(item, _deep = false) {
994
+ return item;
995
+ }
996
+ isMockFunction(fn2) {
997
+ return typeof fn2 === "function" && "__isSpy" in fn2 && fn2.__isSpy;
998
+ }
999
+ clearAllMocks() {
1000
+ __vitest__clearMocks__({ clearMocks: true });
1001
+ spies.forEach((spy) => spy.mockClear());
1002
+ return this;
1003
+ }
1004
+ resetAllMocks() {
1005
+ __vitest__clearMocks__({ mockReset: true });
1006
+ spies.forEach((spy) => spy.mockReset());
1007
+ return this;
1008
+ }
1009
+ restoreAllMocks() {
1010
+ __vitest__clearMocks__({ restoreMocks: true });
1011
+ spies.forEach((spy) => spy.mockRestore());
1012
+ return this;
1013
+ }
1014
+ }
1015
+ const vitest = new VitestUtils();
1016
+ const vi = vitest;
1017
+
1018
+ export { JestChaiExpect as J, getDefaultHookTimeout as a, getState as b, suite as c, describe as d, vi as e, equals as f, getCurrentSuite as g, iterableEquality as h, it as i, subsetEquality as j, isA as k, clearContext as l, defaultSuite as m, setHooks as n, getHooks as o, context as p, getFn as q, setState as s, test as t, vitest as v, withTimeout as w };