vitest 0.0.121 → 0.0.122

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.
@@ -1,1122 +0,0 @@
1
- import { n as noop, i as isObject } from './index-090545ef.js';
2
- import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './_commonjsHelpers-c9e3b764.js';
3
- import { a as spyOn, f as fn, s as spies } from './jest-mock-038a01b3.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 = new WeakMap();
90
- const hooksMap = 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: "",
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: "",
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
- function equals(a, b, customTesters, strictCheck) {
203
- customTesters = customTesters || [];
204
- return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey);
205
- }
206
- function isAsymmetric(obj) {
207
- return !!obj && isA("Function", obj.asymmetricMatch);
208
- }
209
- function hasAsymmetric(obj, seen = new Set()) {
210
- if (seen.has(obj))
211
- return false;
212
- seen.add(obj);
213
- if (isAsymmetric(obj))
214
- return true;
215
- if (Array.isArray(obj))
216
- return obj.some((i) => hasAsymmetric(i, seen));
217
- if (obj instanceof Set)
218
- return Array.from(obj).some((i) => hasAsymmetric(i, seen));
219
- if (isObject(obj))
220
- return Object.values(obj).some((v) => hasAsymmetric(v, seen));
221
- return false;
222
- }
223
- function asymmetricMatch(a, b) {
224
- const asymmetricA = isAsymmetric(a);
225
- const asymmetricB = isAsymmetric(b);
226
- if (asymmetricA && asymmetricB)
227
- return void 0;
228
- if (asymmetricA)
229
- return a.asymmetricMatch(b);
230
- if (asymmetricB)
231
- return b.asymmetricMatch(a);
232
- }
233
- function eq(a, b, aStack, bStack, customTesters, hasKey2) {
234
- let result = true;
235
- const asymmetricResult = asymmetricMatch(a, b);
236
- if (asymmetricResult !== void 0)
237
- return asymmetricResult;
238
- for (let i = 0; i < customTesters.length; i++) {
239
- const customTesterResult = customTesters[i](a, b);
240
- if (customTesterResult !== void 0)
241
- return customTesterResult;
242
- }
243
- if (a instanceof Error && b instanceof Error)
244
- return a.message === b.message;
245
- if (Object.is(a, b))
246
- return true;
247
- if (a === null || b === null)
248
- return a === b;
249
- const className = Object.prototype.toString.call(a);
250
- if (className !== Object.prototype.toString.call(b))
251
- return false;
252
- switch (className) {
253
- case "[object Boolean]":
254
- case "[object String]":
255
- case "[object Number]":
256
- if (typeof a !== typeof b) {
257
- return false;
258
- } else if (typeof a !== "object" && typeof b !== "object") {
259
- return Object.is(a, b);
260
- } else {
261
- return Object.is(a.valueOf(), b.valueOf());
262
- }
263
- case "[object Date]":
264
- return +a === +b;
265
- case "[object RegExp]":
266
- return a.source === b.source && a.flags === b.flags;
267
- }
268
- if (typeof a !== "object" || typeof b !== "object")
269
- return false;
270
- if (isDomNode(a) && isDomNode(b))
271
- return a.isEqualNode(b);
272
- let length = aStack.length;
273
- while (length--) {
274
- if (aStack[length] === a)
275
- return bStack[length] === b;
276
- else if (bStack[length] === b)
277
- return false;
278
- }
279
- aStack.push(a);
280
- bStack.push(b);
281
- if (className === "[object Array]" && a.length !== b.length)
282
- return false;
283
- const aKeys = keys(a, hasKey2);
284
- let key;
285
- let size = aKeys.length;
286
- if (keys(b, hasKey2).length !== size)
287
- return false;
288
- while (size--) {
289
- key = aKeys[size];
290
- result = hasKey2(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey2);
291
- if (!result)
292
- return false;
293
- }
294
- aStack.pop();
295
- bStack.pop();
296
- return result;
297
- }
298
- function keys(obj, hasKey2) {
299
- const keys2 = [];
300
- for (const key in obj) {
301
- if (hasKey2(obj, key))
302
- keys2.push(key);
303
- }
304
- return keys2.concat(Object.getOwnPropertySymbols(obj).filter((symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable));
305
- }
306
- function hasDefinedKey(obj, key) {
307
- return hasKey(obj, key) && obj[key] !== void 0;
308
- }
309
- function hasKey(obj, key) {
310
- return Object.prototype.hasOwnProperty.call(obj, key);
311
- }
312
- function isA(typeName, value) {
313
- return Object.prototype.toString.apply(value) === `[object ${typeName}]`;
314
- }
315
- function isDomNode(obj) {
316
- return obj !== null && typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string" && typeof obj.isEqualNode === "function";
317
- }
318
- const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@";
319
- const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@";
320
- const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@";
321
- function isImmutableUnorderedKeyed(maybeKeyed) {
322
- return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL] && !maybeKeyed[IS_ORDERED_SENTINEL]);
323
- }
324
- function isImmutableUnorderedSet(maybeSet) {
325
- return !!(maybeSet && maybeSet[IS_SET_SENTINEL] && !maybeSet[IS_ORDERED_SENTINEL]);
326
- }
327
- const IteratorSymbol = Symbol.iterator;
328
- const hasIterator = (object) => !!(object != null && object[IteratorSymbol]);
329
- const iterableEquality = (a, b, aStack = [], bStack = []) => {
330
- if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b))
331
- return void 0;
332
- if (a.constructor !== b.constructor)
333
- return false;
334
- let length = aStack.length;
335
- while (length--) {
336
- if (aStack[length] === a)
337
- return bStack[length] === b;
338
- }
339
- aStack.push(a);
340
- bStack.push(b);
341
- const iterableEqualityWithStack = (a2, b2) => iterableEquality(a2, b2, [...aStack], [...bStack]);
342
- if (a.size !== void 0) {
343
- if (a.size !== b.size) {
344
- return false;
345
- } else if (isA("Set", a) || isImmutableUnorderedSet(a)) {
346
- let allFound = true;
347
- for (const aValue of a) {
348
- if (!b.has(aValue)) {
349
- let has = false;
350
- for (const bValue of b) {
351
- const isEqual = equals(aValue, bValue, [iterableEqualityWithStack]);
352
- if (isEqual === true)
353
- has = true;
354
- }
355
- if (has === false) {
356
- allFound = false;
357
- break;
358
- }
359
- }
360
- }
361
- aStack.pop();
362
- bStack.pop();
363
- return allFound;
364
- } else if (isA("Map", a) || isImmutableUnorderedKeyed(a)) {
365
- let allFound = true;
366
- for (const aEntry of a) {
367
- if (!b.has(aEntry[0]) || !equals(aEntry[1], b.get(aEntry[0]), [iterableEqualityWithStack])) {
368
- let has = false;
369
- for (const bEntry of b) {
370
- const matchedKey = equals(aEntry[0], bEntry[0], [
371
- iterableEqualityWithStack
372
- ]);
373
- let matchedValue = false;
374
- if (matchedKey === true) {
375
- matchedValue = equals(aEntry[1], bEntry[1], [
376
- iterableEqualityWithStack
377
- ]);
378
- }
379
- if (matchedValue === true)
380
- has = true;
381
- }
382
- if (has === false) {
383
- allFound = false;
384
- break;
385
- }
386
- }
387
- }
388
- aStack.pop();
389
- bStack.pop();
390
- return allFound;
391
- }
392
- }
393
- const bIterator = b[IteratorSymbol]();
394
- for (const aValue of a) {
395
- const nextB = bIterator.next();
396
- if (nextB.done || !equals(aValue, nextB.value, [iterableEqualityWithStack]))
397
- return false;
398
- }
399
- if (!bIterator.next().done)
400
- return false;
401
- aStack.pop();
402
- bStack.pop();
403
- return true;
404
- };
405
- const hasPropertyInObject = (object, key) => {
406
- const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype;
407
- if (shouldTerminate)
408
- return false;
409
- return Object.prototype.hasOwnProperty.call(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key);
410
- };
411
- const isObjectWithKeys = (a) => isObject(a) && !(a instanceof Error) && !(a instanceof Array) && !(a instanceof Date);
412
- const subsetEquality = (object, subset) => {
413
- const subsetEqualityWithContext = (seenReferences = new WeakMap()) => (object2, subset2) => {
414
- if (!isObjectWithKeys(subset2))
415
- return void 0;
416
- return Object.keys(subset2).every((key) => {
417
- if (isObjectWithKeys(subset2[key])) {
418
- if (seenReferences.has(subset2[key]))
419
- return equals(object2[key], subset2[key], [iterableEquality]);
420
- seenReferences.set(subset2[key], true);
421
- }
422
- const result = object2 != null && hasPropertyInObject(object2, key) && equals(object2[key], subset2[key], [
423
- iterableEquality,
424
- subsetEqualityWithContext(seenReferences)
425
- ]);
426
- seenReferences.delete(subset2[key]);
427
- return result;
428
- });
429
- };
430
- return subsetEqualityWithContext()(object, subset);
431
- };
432
- const typeEquality = (a, b) => {
433
- if (a == null || b == null || a.constructor === b.constructor)
434
- return void 0;
435
- return false;
436
- };
437
- const arrayBufferEquality = (a, b) => {
438
- if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer))
439
- return void 0;
440
- const dataViewA = new DataView(a);
441
- const dataViewB = new DataView(b);
442
- if (dataViewA.byteLength !== dataViewB.byteLength)
443
- return false;
444
- for (let i = 0; i < dataViewA.byteLength; i++) {
445
- if (dataViewA.getUint8(i) !== dataViewB.getUint8(i))
446
- return false;
447
- }
448
- return true;
449
- };
450
- const sparseArrayEquality = (a, b) => {
451
- if (!Array.isArray(a) || !Array.isArray(b))
452
- return void 0;
453
- const aKeys = Object.keys(a);
454
- const bKeys = Object.keys(b);
455
- return equals(a, b, [iterableEquality, typeEquality], true) && equals(aKeys, bKeys);
456
- };
457
-
458
- const MATCHERS_OBJECT = Symbol.for("matchers-object");
459
- if (!Object.prototype.hasOwnProperty.call(global, MATCHERS_OBJECT)) {
460
- const defaultState = {
461
- assertionCalls: 0,
462
- isExpectingAssertions: false,
463
- isExpectingAssertionsError: null,
464
- expectedAssertionsNumber: null,
465
- expectedAssertionsNumberError: null
466
- };
467
- Object.defineProperty(global, MATCHERS_OBJECT, {
468
- value: {
469
- state: defaultState
470
- }
471
- });
472
- }
473
- const getState = () => global[MATCHERS_OBJECT].state;
474
- const setState = (state) => {
475
- Object.assign(global[MATCHERS_OBJECT].state, state);
476
- };
477
- const JestChaiExpect = (chai, utils) => {
478
- function def(name, fn) {
479
- const addMethod = (n) => {
480
- utils.addMethod(chai.Assertion.prototype, n, fn);
481
- };
482
- if (Array.isArray(name))
483
- name.forEach((n) => addMethod(n));
484
- else
485
- addMethod(name);
486
- }
487
- const chaiEqual = chai.Assertion.prototype.equal;
488
- def("chaiEqual", function(...args) {
489
- return chaiEqual.apply(this, args);
490
- });
491
- utils.overwriteMethod(chai.Assertion.prototype, "equal", (_super) => {
492
- return function(...args) {
493
- const expected = args[0];
494
- const actual = utils.flag(this, "object");
495
- if (hasAsymmetric(expected)) {
496
- this.assert(equals(actual, expected, void 0, true), "not match with #{act}", "should not match with #{act}", actual, expected);
497
- } else {
498
- _super.apply(this, args);
499
- }
500
- };
501
- });
502
- utils.overwriteMethod(chai.Assertion.prototype, "eql", (_super) => {
503
- return function(...args) {
504
- const expected = args[0];
505
- const actual = utils.flag(this, "object");
506
- if (hasAsymmetric(expected)) {
507
- this.assert(equals(actual, expected), "not match with #{exp}", "should not match with #{exp}", expected, actual);
508
- } else {
509
- _super.apply(this, args);
510
- }
511
- };
512
- });
513
- def("toEqual", function(expected) {
514
- return this.eql(expected);
515
- });
516
- def("toStrictEqual", function(expected) {
517
- const obj = utils.flag(this, "object");
518
- const equal = equals(obj, expected, [
519
- iterableEquality,
520
- typeEquality,
521
- sparseArrayEquality,
522
- arrayBufferEquality
523
- ], true);
524
- return this.assert(equal, "expected #{this} to strictly equal #{exp}", "expected #{this} to not strictly equal #{exp}", expected, obj);
525
- });
526
- def("toBe", function(expected) {
527
- return this.equal(expected);
528
- });
529
- def("toMatchObject", function(expected) {
530
- return this.containSubset(expected);
531
- });
532
- def("toMatch", function(expected) {
533
- if (typeof expected === "string")
534
- return this.include(expected);
535
- else
536
- return this.match(expected);
537
- });
538
- def("toContain", function(item) {
539
- return this.contain(item);
540
- });
541
- def("toContainEqual", function(expected) {
542
- const obj = utils.flag(this, "object");
543
- const index = Array.from(obj).findIndex((item) => {
544
- try {
545
- chai.assert.deepEqual(item, expected);
546
- } catch {
547
- return false;
548
- }
549
- return true;
550
- });
551
- this.assert(index !== -1, "expected #{this} to deep equally contain #{exp}", "expected #{this} to not deep equally contain #{exp}", expected);
552
- });
553
- def("toBeTruthy", function() {
554
- const obj = utils.flag(this, "object");
555
- this.assert(Boolean(obj), "expected #{this} to be truthy", "expected #{this} to not be truthy", obj);
556
- });
557
- def("toBeFalsy", function() {
558
- const obj = utils.flag(this, "object");
559
- this.assert(!obj, "expected #{this} to be falsy", "expected #{this} to not be falsy", obj);
560
- });
561
- def("toBeGreaterThan", function(expected) {
562
- return this.to.greaterThan(expected);
563
- });
564
- def("toBeGreaterThanOrEqual", function(expected) {
565
- return this.to.greaterThanOrEqual(expected);
566
- });
567
- def("toBeLessThan", function(expected) {
568
- return this.to.lessThan(expected);
569
- });
570
- def("toBeLessThanOrEqual", function(expected) {
571
- return this.to.lessThanOrEqual(expected);
572
- });
573
- def("toBeNaN", function() {
574
- return this.be.NaN;
575
- });
576
- def("toBeUndefined", function() {
577
- return this.be.undefined;
578
- });
579
- def("toBeNull", function() {
580
- return this.be.null;
581
- });
582
- def("toBeDefined", function() {
583
- const negate = utils.flag(this, "negate");
584
- utils.flag(this, "negate", false);
585
- if (negate)
586
- return this.be.undefined;
587
- return this.not.be.undefined;
588
- });
589
- def("toBeInstanceOf", function(obj) {
590
- return this.instanceOf(obj);
591
- });
592
- def("toHaveLength", function(length) {
593
- return this.have.length(length);
594
- });
595
- def("toHaveProperty", function(...args) {
596
- return this.have.deep.nested.property(...args);
597
- });
598
- def("toBeCloseTo", function(number, numDigits = 2) {
599
- utils.expectTypes(this, ["number"]);
600
- return this.closeTo(number, numDigits);
601
- });
602
- function isSpy(putativeSpy) {
603
- return typeof putativeSpy === "function" && "__isSpy" in putativeSpy && putativeSpy.__isSpy;
604
- }
605
- const assertIsMock = (assertion) => {
606
- if (!isSpy(assertion._obj))
607
- throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`);
608
- };
609
- const getSpy = (assertion) => {
610
- assertIsMock(assertion);
611
- return assertion._obj;
612
- };
613
- def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) {
614
- const spy = getSpy(this);
615
- const spyName = spy.getMockName();
616
- return this.assert(spy.callCount === number, `expected "${spyName}" to be called #{exp} times`, `expected "${spyName}" to not be called #{exp} times`, number, spy.callCount);
617
- });
618
- def("toHaveBeenCalledOnce", function() {
619
- const spy = getSpy(this);
620
- const spyName = spy.getMockName();
621
- return this.assert(spy.callCount === 1, `expected "${spyName}" to be called once`, `expected "${spyName}" to not be called once`, 1, spy.callCount);
622
- });
623
- def(["toHaveBeenCalled", "toBeCalled"], function() {
624
- const spy = getSpy(this);
625
- const spyName = spy.getMockName();
626
- return this.assert(spy.called, `expected "${spyName}" to be called at least once`, `expected "${spyName}" to not be called at all`, true, spy.called);
627
- });
628
- def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) {
629
- const spy = getSpy(this);
630
- const spyName = spy.getMockName();
631
- const pass = spy.calls.some((callArg) => equals(callArg, args));
632
- return this.assert(pass, `expected "${spyName}" to be called with arguments: #{exp}`, `expected "${spyName}" to not be called with arguments: #{exp}`, args, spy.calls);
633
- });
634
- const ordinalOf = (i) => {
635
- const j = i % 10;
636
- const k = i % 100;
637
- if (j === 1 && k !== 11)
638
- return `${i}st`;
639
- if (j === 2 && k !== 12)
640
- return `${i}nd`;
641
- if (j === 3 && k !== 13)
642
- return `${i}rd`;
643
- return `${i}th`;
644
- };
645
- def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) {
646
- const spy = getSpy(this);
647
- const spyName = spy.getMockName();
648
- const nthCall = spy.calls[times - 1];
649
- this.assert(equals(nthCall, args), `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}`, `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall);
650
- });
651
- def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) {
652
- const spy = getSpy(this);
653
- const spyName = spy.getMockName();
654
- const lastCall = spy.calls[spy.calls.length - 1];
655
- this.assert(equals(lastCall, args), `expected last "${spyName}" call to have been called with #{exp}`, `expected last "${spyName}" call to not have been called with #{exp}`, args, lastCall);
656
- });
657
- def(["toThrow", "toThrowError"], function(expected) {
658
- const negate = utils.flag(this, "negate");
659
- if (negate)
660
- this.not.to.throw(expected);
661
- else
662
- this.to.throw(expected);
663
- });
664
- def(["toHaveReturned", "toReturn"], function() {
665
- const spy = getSpy(this);
666
- const spyName = spy.getMockName();
667
- const calledAndNotThrew = spy.called && !spy.results.some(([type]) => type === "error");
668
- this.assert(calledAndNotThrew, `expected "${spyName}" to be successfully called at least once`, `expected "${spyName}" to not be successfully called`, calledAndNotThrew, !calledAndNotThrew);
669
- });
670
- def(["toHaveReturnedTimes", "toReturnTimes"], function(times) {
671
- const spy = getSpy(this);
672
- const spyName = spy.getMockName();
673
- const successfullReturns = spy.results.reduce((success, [type]) => type === "error" ? success : ++success, 0);
674
- this.assert(successfullReturns === times, `expected "${spyName}" to be successfully called ${times} times`, `expected "${spyName}" to not be successfully called ${times} times`, `expected number of returns: ${times}`, `received number of returns: ${successfullReturns}`);
675
- });
676
- def(["toHaveReturnedWith", "toReturnWith"], function(value) {
677
- const spy = getSpy(this);
678
- const spyName = spy.getMockName();
679
- const pass = spy.results.some(([type, result]) => type === "ok" && equals(value, result));
680
- this.assert(pass, `expected "${spyName}" to be successfully called with #{exp}`, `expected "${spyName}" to not be successfully called with #{exp}`, value);
681
- });
682
- def(["toHaveLastReturnedWith", "lastReturnedWith"], function(value) {
683
- const spy = getSpy(this);
684
- const spyName = spy.getMockName();
685
- const lastResult = spy.returns[spy.returns.length - 1];
686
- const pass = equals(lastResult, value);
687
- this.assert(pass, `expected last "${spyName}" call to return #{exp}`, `expected last "${spyName}" call to not return #{exp}`, value, lastResult);
688
- });
689
- def(["toHaveNthReturnedWith", "nthReturnedWith"], function(nthCall, value) {
690
- const spy = getSpy(this);
691
- const spyName = spy.getMockName();
692
- const isNot = utils.flag(this, "negate");
693
- const [callType, callResult] = spy.results[nthCall - 1];
694
- const ordinalCall = `${ordinalOf(nthCall)} call`;
695
- if (!isNot && callType === "error")
696
- chai.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`);
697
- const nthCallReturn = equals(callResult, value);
698
- this.assert(nthCallReturn, `expected ${ordinalCall} "${spyName}" call to return #{exp}`, `expected ${ordinalCall} "${spyName}" call to not return #{exp}`, value, callResult);
699
- });
700
- utils.addProperty(chai.Assertion.prototype, "resolves", function() {
701
- utils.flag(this, "promise", "resolves");
702
- const obj = utils.flag(this, "object");
703
- const proxy = new Proxy(this, {
704
- get: (target, key, reciever) => {
705
- const result = Reflect.get(target, key, reciever);
706
- if (typeof result !== "function")
707
- return result instanceof chai.Assertion ? proxy : result;
708
- return async (...args) => {
709
- return obj.then((value) => {
710
- utils.flag(this, "object", value);
711
- return result.call(this, ...args);
712
- }, (err) => {
713
- throw new Error(`promise rejected ${err} instead of resolving`);
714
- });
715
- };
716
- }
717
- });
718
- return proxy;
719
- });
720
- utils.addProperty(chai.Assertion.prototype, "rejects", function() {
721
- utils.flag(this, "promise", "rejects");
722
- const obj = utils.flag(this, "object");
723
- const wrapper = typeof obj === "function" ? obj() : obj;
724
- const proxy = new Proxy(this, {
725
- get: (target, key, reciever) => {
726
- const result = Reflect.get(target, key, reciever);
727
- if (typeof result !== "function")
728
- return result instanceof chai.Assertion ? proxy : result;
729
- return async (...args) => {
730
- return wrapper.then((value) => {
731
- throw new Error(`promise resolved ${value} instead of rejecting`);
732
- }, (err) => {
733
- utils.flag(this, "object", err);
734
- return result.call(this, ...args);
735
- });
736
- };
737
- }
738
- });
739
- return proxy;
740
- });
741
- utils.addMethod(chai.expect, "assertions", function assertions(expected) {
742
- const error = new Error(`expected number of assertions to be ${expected}, but got ${getState().assertionCalls}`);
743
- if (Error.captureStackTrace)
744
- Error.captureStackTrace(error, assertions);
745
- setState({
746
- expectedAssertionsNumber: expected,
747
- expectedAssertionsNumberError: error
748
- });
749
- });
750
- utils.addMethod(chai.expect, "hasAssertions", function hasAssertions() {
751
- const error = new Error("expected any number of assertion, but got none");
752
- if (Error.captureStackTrace)
753
- Error.captureStackTrace(error, hasAssertions);
754
- setState({
755
- isExpectingAssertions: true,
756
- isExpectingAssertionsError: error
757
- });
758
- });
759
- };
760
-
761
- var mockdate$1 = {exports: {}};
762
-
763
- (function (module, exports) {
764
- (function (global, factory) {
765
- factory(exports) ;
766
- }(commonjsGlobal, (function (exports) {
767
- /*! *****************************************************************************
768
- Copyright (c) Microsoft Corporation.
769
-
770
- Permission to use, copy, modify, and/or distribute this software for any
771
- purpose with or without fee is hereby granted.
772
-
773
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
774
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
775
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
776
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
777
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
778
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
779
- PERFORMANCE OF THIS SOFTWARE.
780
- ***************************************************************************** */
781
- /* global Reflect, Promise */
782
-
783
- var extendStatics = function(d, b) {
784
- extendStatics = Object.setPrototypeOf ||
785
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
786
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
787
- return extendStatics(d, b);
788
- };
789
-
790
- function __extends(d, b) {
791
- if (typeof b !== "function" && b !== null)
792
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
793
- extendStatics(d, b);
794
- function __() { this.constructor = d; }
795
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
796
- }
797
-
798
- var RealDate = Date;
799
- var now = null;
800
- var MockDate = /** @class */ (function (_super) {
801
- __extends(Date, _super);
802
- function Date(y, m, d, h, M, s, ms) {
803
- _super.call(this) || this;
804
- var date;
805
- switch (arguments.length) {
806
- case 0:
807
- if (now !== null) {
808
- date = new RealDate(now.valueOf());
809
- }
810
- else {
811
- date = new RealDate();
812
- }
813
- break;
814
- case 1:
815
- date = new RealDate(y);
816
- break;
817
- default:
818
- d = typeof d === 'undefined' ? 1 : d;
819
- h = h || 0;
820
- M = M || 0;
821
- s = s || 0;
822
- ms = ms || 0;
823
- date = new RealDate(y, m, d, h, M, s, ms);
824
- break;
825
- }
826
- return date;
827
- }
828
- return Date;
829
- }(RealDate));
830
- MockDate.prototype = RealDate.prototype;
831
- MockDate.UTC = RealDate.UTC;
832
- MockDate.now = function () {
833
- return new MockDate().valueOf();
834
- };
835
- MockDate.parse = function (dateString) {
836
- return RealDate.parse(dateString);
837
- };
838
- MockDate.toString = function () {
839
- return RealDate.toString();
840
- };
841
- function set(date) {
842
- var dateObj = new Date(date.valueOf());
843
- if (isNaN(dateObj.getTime())) {
844
- throw new TypeError('mockdate: The time set is an invalid date: ' + date);
845
- }
846
- // @ts-ignore
847
- Date = MockDate;
848
- now = dateObj.valueOf();
849
- }
850
- function reset() {
851
- Date = RealDate;
852
- }
853
- var mockdate = {
854
- set: set,
855
- reset: reset,
856
- };
857
-
858
- exports.default = mockdate;
859
- exports.reset = reset;
860
- exports.set = set;
861
-
862
- Object.defineProperty(exports, '__esModule', { value: true });
863
-
864
- })));
865
- }(mockdate$1, mockdate$1.exports));
866
-
867
- var mockdate = /*@__PURE__*/getDefaultExportFromCjs(mockdate$1.exports);
868
-
869
- const originalSetTimeout = global.setTimeout;
870
- const originalSetInterval = global.setInterval;
871
- const originalClearTimeout = global.clearTimeout;
872
- const originalClearInterval = global.clearInterval;
873
- const MAX_LOOPS = 1e4;
874
- var QueueTaskType;
875
- (function(QueueTaskType2) {
876
- QueueTaskType2["Interval"] = "interval";
877
- QueueTaskType2["Timeout"] = "timeout";
878
- QueueTaskType2["Immediate"] = "immediate";
879
- })(QueueTaskType || (QueueTaskType = {}));
880
- const assertEvery = (assertions, message) => {
881
- if (assertions.some((a) => !a))
882
- throw new Error(message);
883
- };
884
- const assertMaxLoop = (times) => {
885
- if (times >= MAX_LOOPS)
886
- throw new Error("setTimeout/setInterval called 10 000 times. It's possible it stuck in an infinite loop.");
887
- };
888
- const getNodeTimeout = (id) => {
889
- const timer = {
890
- ref: () => timer,
891
- unref: () => timer,
892
- hasRef: () => true,
893
- refresh: () => timer,
894
- [Symbol.toPrimitive]: () => id
895
- };
896
- return timer;
897
- };
898
- class FakeTimers {
899
- constructor() {
900
- this._advancedTime = 0;
901
- this._nestedTime = {};
902
- this._scopeId = 0;
903
- this._isNested = false;
904
- this._isOnlyPending = false;
905
- this._spyid = 0;
906
- this._isMocked = false;
907
- this._tasksQueue = [];
908
- this._queueCount = 0;
909
- }
910
- useFakeTimers() {
911
- this._isMocked = true;
912
- this.reset();
913
- const spyFactory = (spyType, resultBuilder) => {
914
- return (cb, ms = 0) => {
915
- const id = ++this._spyid;
916
- const nestedTo = Object.entries(this._nestedTime).filter(([key]) => Number(key) <= this._scopeId);
917
- const nestedMs = nestedTo.reduce((total, [, ms2]) => total + ms2, ms);
918
- const call = { id, cb, ms, nestedMs, scopeId: this._scopeId };
919
- const task = { type: spyType, call, nested: this._isNested };
920
- this.pushTask(task);
921
- return resultBuilder(id, cb);
922
- };
923
- };
924
- this._setTimeout = spyOn(global, "setTimeout").mockImplementation(spyFactory(QueueTaskType.Timeout, getNodeTimeout));
925
- this._setInterval = spyOn(global, "setInterval").mockImplementation(spyFactory(QueueTaskType.Interval, getNodeTimeout));
926
- const clearTimerFactory = (spyType) => (id) => {
927
- if (id === void 0)
928
- return;
929
- const index = this._tasksQueue.findIndex(({ call, type }) => type === spyType && call.id === Number(id));
930
- if (index !== -1)
931
- this._tasksQueue.splice(index, 1);
932
- };
933
- this._clearTimeout = spyOn(global, "clearTimeout").mockImplementation(clearTimerFactory(QueueTaskType.Timeout));
934
- this._clearInterval = spyOn(global, "clearInterval").mockImplementation(clearTimerFactory(QueueTaskType.Interval));
935
- }
936
- useRealTimers() {
937
- this._isMocked = false;
938
- this.reset();
939
- global.setTimeout = originalSetTimeout;
940
- global.setInterval = originalSetInterval;
941
- global.clearTimeout = originalClearTimeout;
942
- global.clearInterval = originalClearInterval;
943
- }
944
- runOnlyPendingTimers() {
945
- this.assertMocked();
946
- this._isOnlyPending = true;
947
- this.runQueue();
948
- }
949
- runAllTimers() {
950
- this.assertMocked();
951
- this.runQueue();
952
- }
953
- advanceTimersByTime(ms) {
954
- this.assertMocked();
955
- this._advancedTime += ms;
956
- this.runQueue();
957
- }
958
- advanceTimersToNextTimer() {
959
- this.assertMocked();
960
- this.callQueueItem(0);
961
- }
962
- getTimerCount() {
963
- this.assertMocked();
964
- return this._tasksQueue.length;
965
- }
966
- reset() {
967
- var _a, _b, _c, _d;
968
- this._advancedTime = 0;
969
- this._nestedTime = {};
970
- this._isNested = false;
971
- this._isOnlyPending = false;
972
- this._spyid = 0;
973
- this._queueCount = 0;
974
- this._tasksQueue = [];
975
- (_a = this._clearInterval) == null ? void 0 : _a.mockRestore();
976
- (_b = this._clearTimeout) == null ? void 0 : _b.mockRestore();
977
- (_c = this._setInterval) == null ? void 0 : _c.mockRestore();
978
- (_d = this._setTimeout) == null ? void 0 : _d.mockRestore();
979
- }
980
- callQueueItem(index) {
981
- var _a, _b;
982
- const task = this._tasksQueue[index];
983
- if (!task)
984
- return;
985
- const { call, type } = task;
986
- this._scopeId = call.id;
987
- this._isNested = true;
988
- (_a = this._nestedTime)[_b = call.id] ?? (_a[_b] = 0);
989
- this._nestedTime[call.id] += call.ms;
990
- if (type === "timeout") {
991
- this.removeTask(index);
992
- } else if (type === "interval") {
993
- call.nestedMs += call.ms;
994
- const nestedMs = call.nestedMs;
995
- const closestTask = this._tasksQueue.findIndex(({ type: type2, call: call2 }) => type2 === "interval" && call2.nestedMs < nestedMs);
996
- if (closestTask !== -1 && closestTask !== index)
997
- this.ensureQueueOrder();
998
- }
999
- call.cb();
1000
- this._queueCount++;
1001
- }
1002
- runQueue() {
1003
- let index = 0;
1004
- while (this._tasksQueue[index]) {
1005
- assertMaxLoop(this._queueCount);
1006
- const { call, nested } = this._tasksQueue[index];
1007
- if (this._advancedTime && call.nestedMs > this._advancedTime)
1008
- break;
1009
- if (this._isOnlyPending && nested) {
1010
- index++;
1011
- continue;
1012
- }
1013
- this.callQueueItem(index);
1014
- }
1015
- }
1016
- removeTask(index) {
1017
- if (index === 0)
1018
- this._tasksQueue.shift();
1019
- else
1020
- this._tasksQueue.splice(index, 1);
1021
- }
1022
- pushTask(task) {
1023
- this._tasksQueue.push(task);
1024
- this.ensureQueueOrder();
1025
- }
1026
- ensureQueueOrder() {
1027
- this._tasksQueue.sort((t1, t2) => {
1028
- const diff = t1.call.nestedMs - t2.call.nestedMs;
1029
- if (diff === 0) {
1030
- if (t1.type === QueueTaskType.Immediate && t2.type !== QueueTaskType.Immediate)
1031
- return 1;
1032
- return 0;
1033
- }
1034
- return diff;
1035
- });
1036
- }
1037
- assertMocked() {
1038
- assertEvery([
1039
- this._isMocked,
1040
- this._setTimeout,
1041
- this._setInterval,
1042
- this._clearTimeout,
1043
- this._clearInterval
1044
- ], 'timers are not mocked. try calling "vitest.useFakeTimers()" first');
1045
- }
1046
- }
1047
-
1048
- class VitestUtils {
1049
- constructor() {
1050
- this.spyOn = spyOn;
1051
- this.fn = fn;
1052
- this._timers = new FakeTimers();
1053
- this._mockedDate = null;
1054
- }
1055
- useFakeTimers() {
1056
- return this._timers.useFakeTimers();
1057
- }
1058
- useRealTimers() {
1059
- return this._timers.useRealTimers();
1060
- }
1061
- runOnlyPendingTimers() {
1062
- return this._timers.runOnlyPendingTimers();
1063
- }
1064
- runAllTimers() {
1065
- return this._timers.runAllTimers();
1066
- }
1067
- advanceTimersByTime(ms) {
1068
- return this._timers.advanceTimersByTime(ms);
1069
- }
1070
- advanceTimersToNextTimer() {
1071
- return this._timers.advanceTimersToNextTimer();
1072
- }
1073
- getTimerCount() {
1074
- return this._timers.getTimerCount();
1075
- }
1076
- mockCurrentDate(date) {
1077
- this._mockedDate = date;
1078
- mockdate.set(date);
1079
- }
1080
- restoreCurrentDate() {
1081
- this._mockedDate = null;
1082
- mockdate.reset();
1083
- }
1084
- getMockedDate() {
1085
- return this._mockedDate;
1086
- }
1087
- mock(path, factory) {
1088
- }
1089
- unmock(path) {
1090
- }
1091
- async importActual(path) {
1092
- return {};
1093
- }
1094
- async importMock(path) {
1095
- return {};
1096
- }
1097
- mocked(item, _deep = false) {
1098
- return item;
1099
- }
1100
- isMockFunction(fn2) {
1101
- return typeof fn2 === "function" && "__isSpy" in fn2 && fn2.__isSpy;
1102
- }
1103
- clearAllMocks() {
1104
- __vitest__clearMocks__({ clearMocks: true });
1105
- spies.forEach((spy) => spy.mockClear());
1106
- return this;
1107
- }
1108
- resetAllMocks() {
1109
- __vitest__clearMocks__({ mockReset: true });
1110
- spies.forEach((spy) => spy.mockReset());
1111
- return this;
1112
- }
1113
- restoreAllMocks() {
1114
- __vitest__clearMocks__({ restoreMocks: true });
1115
- spies.forEach((spy) => spy.mockRestore());
1116
- return this;
1117
- }
1118
- }
1119
- const vitest = new VitestUtils();
1120
- const vi = vitest;
1121
-
1122
- 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 };