vitest 0.27.2 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE.md +4 -93
  2. package/browser.d.ts +1 -1
  3. package/dist/browser.d.ts +11 -13
  4. package/dist/browser.js +10 -34
  5. package/dist/{chunk-api-setup.029198e3.js → chunk-api-setup.52751a38.js} +27 -12
  6. package/dist/chunk-constants.797d3ebf.js +42 -0
  7. package/dist/{chunk-env-node.787e9561.js → chunk-env-node.ffd1183b.js} +26 -0
  8. package/dist/{chunk-install-pkg.7b006b3e.js → chunk-install-pkg.cfd23146.js} +51 -11
  9. package/dist/chunk-integrations-coverage.48e6286b.js +3993 -0
  10. package/dist/chunk-integrations-globals.0d5f50f0.js +29 -0
  11. package/dist/chunk-integrations-run-once.38756e30.js +27 -0
  12. package/dist/chunk-integrations-utils.f1f6f1ed.js +118 -0
  13. package/dist/{chunk-node-git.125c9008.js → chunk-node-git.d9ad64ab.js} +6 -7
  14. package/dist/{chunk-snapshot-manager.ce714e21.js → chunk-node-pkg.dcdf4369.js} +12653 -9324
  15. package/dist/{chunk-runtime-mocker.58511c38.js → chunk-runtime-mocker.03017e8c.js} +14 -13
  16. package/dist/{chunk-runtime-rpc.d709e91b.js → chunk-runtime-rpc.9c0386cc.js} +3 -2
  17. package/dist/chunk-runtime-setup.d9302cfd.js +20 -0
  18. package/dist/chunk-snapshot-env.6457638e.js +11 -0
  19. package/dist/chunk-utils-base.977ae74f.js +77 -0
  20. package/dist/chunk-utils-env.860d90c2.js +6 -0
  21. package/dist/chunk-utils-global.442d1d33.js +73 -0
  22. package/dist/{chunk-utils-import.054ab315.js → chunk-utils-import.9911c99d.js} +3289 -169
  23. package/dist/chunk-utils-tasks.1b603032.js +103 -0
  24. package/dist/cli-wrapper.js +8 -6
  25. package/dist/cli.js +18 -15
  26. package/dist/config.cjs +10 -7
  27. package/dist/config.d.ts +22 -4
  28. package/dist/config.js +10 -8
  29. package/dist/entry.js +244 -28
  30. package/dist/env-afee91f0.d.ts +10 -0
  31. package/dist/environments.d.ts +7 -2
  32. package/dist/environments.js +1 -1
  33. package/dist/index.d.ts +160 -11
  34. package/dist/index.js +18 -18
  35. package/dist/loader.js +9 -8
  36. package/dist/node.d.ts +9 -7
  37. package/dist/node.js +20 -17
  38. package/dist/runners-chunk.js +215 -0
  39. package/dist/runners.d.ts +39 -0
  40. package/dist/runners.js +18 -0
  41. package/dist/spy.js +1 -2
  42. package/dist/suite.d.ts +2 -0
  43. package/dist/suite.js +2 -18
  44. package/dist/{types-d97c72c7.d.ts → types-c800444e.d.ts} +196 -437
  45. package/dist/{vendor-index.e6c27006.js → vendor-index.618ca5a1.js} +1078 -10
  46. package/dist/{vendor-index.b0346fe4.js → vendor-index.bdee400f.js} +1 -0
  47. package/dist/worker.js +17 -16
  48. package/package.json +22 -12
  49. package/runners.d.ts +1 -0
  50. package/suite.d.ts +1 -0
  51. package/dist/chunk-integrations-coverage.44413252.js +0 -240
  52. package/dist/chunk-integrations-globals.0024ce21.js +0 -27
  53. package/dist/chunk-mock-date.c543fa3e.js +0 -349
  54. package/dist/chunk-runtime-chain.2da9e75c.js +0 -2595
  55. package/dist/chunk-runtime-error.de671af0.js +0 -144
  56. package/dist/chunk-runtime-setup.35da9209.js +0 -649
  57. package/dist/chunk-utils-env.f4a39d2c.js +0 -228
  58. package/dist/chunk-utils-source-map.5f5d12cf.js +0 -408
  59. package/dist/chunk-utils-timers.52534f96.js +0 -3573
  60. package/dist/index-50755efe.d.ts +0 -258
  61. package/dist/vendor-index.451e37bc.js +0 -1071
  62. package/dist/vendor-index.723a074f.js +0 -102
  63. package/dist/vendor-index.9c919048.js +0 -61
  64. package/dist/vendor-index.9f20a9be.js +0 -6291
@@ -1,2595 +0,0 @@
1
- import util$1 from 'util';
2
- import * as chai$2 from 'chai';
3
- import { AssertionError, util, expect } from 'chai';
4
- import { i as isObject$1, b as getCallLastIndex, s as slash, g as getWorkerState, c as getNames, d as getCurrentEnvironment, e as getFullName, o as objectAttr, n as noop, f as isRunningInTest, h as isRunningInBenchmark } from './chunk-mock-date.c543fa3e.js';
5
- import { c as commonjsGlobal } from './vendor-_commonjsHelpers.addc3445.js';
6
- import c from 'picocolors';
7
- import { c as createPatch, a as stringify, p as plugins_1, f as format_1, s as safeSetTimeout, b as safeClearTimeout } from './chunk-utils-timers.52534f96.js';
8
- import { i as isMockFunction } from './vendor-index.723a074f.js';
9
- import { c as cliTruncate, a as positionToOffset, o as offsetToLineNumber, l as lineSplitRE, b as parseStacktrace } from './chunk-utils-source-map.5f5d12cf.js';
10
- import { r as rpc } from './chunk-runtime-rpc.d709e91b.js';
11
- import fs from 'node:fs';
12
- import { j as join, d as dirname } from './chunk-utils-env.f4a39d2c.js';
13
- import { promises } from 'fs';
14
-
15
- function createChainable(keys, fn) {
16
- function create(context) {
17
- const chain2 = function(...args) {
18
- return fn.apply(context, args);
19
- };
20
- Object.assign(chain2, fn);
21
- chain2.withContext = () => chain2.bind(context);
22
- for (const key of keys) {
23
- Object.defineProperty(chain2, key, {
24
- get() {
25
- return create({ ...context, [key]: true });
26
- }
27
- });
28
- }
29
- return chain2;
30
- }
31
- const chain = create({});
32
- chain.fn = fn;
33
- return chain;
34
- }
35
-
36
- function commonjsRequire(path) {
37
- 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.');
38
- }
39
-
40
- var chaiSubset = {exports: {}};
41
-
42
- (function (module, exports) {
43
- (function() {
44
- (function(chaiSubset) {
45
- if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
46
- return module.exports = chaiSubset;
47
- } else {
48
- return chai.use(chaiSubset);
49
- }
50
- })(function(chai, utils) {
51
- var Assertion = chai.Assertion;
52
- var assertionPrototype = Assertion.prototype;
53
-
54
- Assertion.addMethod('containSubset', function (expected) {
55
- var actual = utils.flag(this, 'object');
56
- var showDiff = chai.config.showDiff;
57
-
58
- assertionPrototype.assert.call(this,
59
- compare(expected, actual),
60
- 'expected #{act} to contain subset #{exp}',
61
- 'expected #{act} to not contain subset #{exp}',
62
- expected,
63
- actual,
64
- showDiff
65
- );
66
- });
67
-
68
- chai.assert.containSubset = function(val, exp, msg) {
69
- new chai.Assertion(val, msg).to.be.containSubset(exp);
70
- };
71
-
72
- function compare(expected, actual) {
73
- if (expected === actual) {
74
- return true;
75
- }
76
- if (typeof(actual) !== typeof(expected)) {
77
- return false;
78
- }
79
- if (typeof(expected) !== 'object' || expected === null) {
80
- return expected === actual;
81
- }
82
- if (!!expected && !actual) {
83
- return false;
84
- }
85
-
86
- if (Array.isArray(expected)) {
87
- if (typeof(actual.length) !== 'number') {
88
- return false;
89
- }
90
- var aa = Array.prototype.slice.call(actual);
91
- return expected.every(function (exp) {
92
- return aa.some(function (act) {
93
- return compare(exp, act);
94
- });
95
- });
96
- }
97
-
98
- if (expected instanceof Date) {
99
- if (actual instanceof Date) {
100
- return expected.getTime() === actual.getTime();
101
- } else {
102
- return false;
103
- }
104
- }
105
-
106
- return Object.keys(expected).every(function (key) {
107
- var eo = expected[key];
108
- var ao = actual[key];
109
- if (typeof(eo) === 'object' && eo !== null && ao !== null) {
110
- return compare(eo, ao);
111
- }
112
- if (typeof(eo) === 'function') {
113
- return eo(ao);
114
- }
115
- return ao === eo;
116
- });
117
- }
118
- });
119
-
120
- }).call(commonjsGlobal);
121
- } (chaiSubset));
122
-
123
- var Subset = chaiSubset.exports;
124
-
125
- function formatLine(line, outputTruncateLength) {
126
- var _a;
127
- return cliTruncate(line, (outputTruncateLength ?? (((_a = process.stdout) == null ? void 0 : _a.columns) || 80)) - 4);
128
- }
129
- function unifiedDiff(actual, expected, options = {}) {
130
- if (actual === expected)
131
- return "";
132
- const { outputTruncateLength, outputDiffLines, outputDiffMaxLines, noColor, showLegend = true } = options;
133
- const indent = " ";
134
- const diffLimit = outputDiffLines || 15;
135
- const diffMaxLines = outputDiffMaxLines || 50;
136
- const counts = {
137
- "+": 0,
138
- "-": 0
139
- };
140
- let previousState = null;
141
- let previousCount = 0;
142
- const str = (str2) => str2;
143
- const dim = noColor ? str : c.dim;
144
- const green = noColor ? str : c.green;
145
- const red = noColor ? str : c.red;
146
- function preprocess(line) {
147
- if (!line || line.match(/\\ No newline/))
148
- return;
149
- const char = line[0];
150
- if ("-+".includes(char)) {
151
- if (previousState !== char) {
152
- previousState = char;
153
- previousCount = 0;
154
- }
155
- previousCount++;
156
- counts[char]++;
157
- if (previousCount === diffLimit)
158
- return dim(`${char} ...`);
159
- else if (previousCount > diffLimit)
160
- return;
161
- }
162
- return line;
163
- }
164
- const msg = createPatch("string", expected, actual);
165
- let lines = msg.split("\n").slice(5).map(preprocess).filter(Boolean);
166
- let moreLines = 0;
167
- const isCompact = counts["+"] === 1 && counts["-"] === 1 && lines.length === 2;
168
- if (lines.length > diffMaxLines) {
169
- const firstDiff = lines.findIndex((line) => line[0] === "-" || line[0] === "+");
170
- const displayLines = lines.slice(firstDiff - 2, diffMaxLines);
171
- const lastDisplayedIndex = firstDiff - 2 + diffMaxLines;
172
- if (lastDisplayedIndex < lines.length)
173
- moreLines = lines.length - lastDisplayedIndex;
174
- lines = displayLines;
175
- }
176
- let formatted = lines.map((line) => {
177
- line = line.replace(/\\"/g, '"');
178
- if (line[0] === "-") {
179
- line = formatLine(line.slice(1), outputTruncateLength);
180
- if (isCompact)
181
- return green(line);
182
- return green(`- ${formatLine(line, outputTruncateLength)}`);
183
- }
184
- if (line[0] === "+") {
185
- line = formatLine(line.slice(1), outputTruncateLength);
186
- if (isCompact)
187
- return red(line);
188
- return red(`+ ${formatLine(line, outputTruncateLength)}`);
189
- }
190
- if (line.match(/@@/))
191
- return "--";
192
- return ` ${line}`;
193
- });
194
- if (moreLines)
195
- formatted.push(dim(`... ${moreLines} more lines`));
196
- if (showLegend) {
197
- if (isCompact) {
198
- formatted = [
199
- `${green("- Expected")} ${formatted[0]}`,
200
- `${red("+ Received")} ${formatted[1]}`
201
- ];
202
- } else {
203
- if (formatted[0].includes('"'))
204
- formatted[0] = formatted[0].replace('"', "");
205
- const last = formatted.length - 1;
206
- if (formatted[last].endsWith('"'))
207
- formatted[last] = formatted[last].slice(0, formatted[last].length - 1);
208
- formatted.unshift(
209
- green(`- Expected - ${counts["-"]}`),
210
- red(`+ Received + ${counts["+"]}`),
211
- ""
212
- );
213
- }
214
- }
215
- return formatted.map((i) => i ? indent + i : i).join("\n");
216
- }
217
-
218
- function assertTypes(value, name, types) {
219
- const receivedType = typeof value;
220
- const pass = types.includes(receivedType);
221
- if (!pass)
222
- throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`);
223
- }
224
- function isObject(item) {
225
- return item != null && typeof item === "object" && !Array.isArray(item);
226
- }
227
-
228
- const MATCHERS_OBJECT = Symbol.for("matchers-object");
229
- const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object");
230
- const GLOBAL_EXPECT = Symbol.for("expect-global");
231
- if (!Object.prototype.hasOwnProperty.call(globalThis, MATCHERS_OBJECT)) {
232
- const globalState = /* @__PURE__ */ new WeakMap();
233
- const matchers = /* @__PURE__ */ Object.create(null);
234
- Object.defineProperty(globalThis, MATCHERS_OBJECT, {
235
- get: () => globalState
236
- });
237
- Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, {
238
- configurable: true,
239
- get: () => ({
240
- state: globalState.get(globalThis[GLOBAL_EXPECT]),
241
- matchers
242
- })
243
- });
244
- }
245
- const getState = (expect) => globalThis[MATCHERS_OBJECT].get(expect);
246
- const setState = (state, expect) => {
247
- const map = globalThis[MATCHERS_OBJECT];
248
- const current = map.get(expect) || {};
249
- Object.assign(current, state);
250
- map.set(expect, current);
251
- };
252
- const EXPECTED_COLOR = c.green;
253
- const RECEIVED_COLOR = c.red;
254
- const INVERTED_COLOR = c.inverse;
255
- const BOLD_WEIGHT = c.bold;
256
- const DIM_COLOR = c.dim;
257
- function matcherHint(matcherName, received = "received", expected = "expected", options = {}) {
258
- const {
259
- comment = "",
260
- isDirectExpectCall = false,
261
- isNot = false,
262
- promise = "",
263
- secondArgument = "",
264
- expectedColor = EXPECTED_COLOR,
265
- receivedColor = RECEIVED_COLOR,
266
- secondArgumentColor = EXPECTED_COLOR
267
- } = options;
268
- let hint = "";
269
- let dimString = "expect";
270
- if (!isDirectExpectCall && received !== "") {
271
- hint += DIM_COLOR(`${dimString}(`) + receivedColor(received);
272
- dimString = ")";
273
- }
274
- if (promise !== "") {
275
- hint += DIM_COLOR(`${dimString}.`) + promise;
276
- dimString = "";
277
- }
278
- if (isNot) {
279
- hint += `${DIM_COLOR(`${dimString}.`)}not`;
280
- dimString = "";
281
- }
282
- if (matcherName.includes(".")) {
283
- dimString += matcherName;
284
- } else {
285
- hint += DIM_COLOR(`${dimString}.`) + matcherName;
286
- dimString = "";
287
- }
288
- if (expected === "") {
289
- dimString += "()";
290
- } else {
291
- hint += DIM_COLOR(`${dimString}(`) + expectedColor(expected);
292
- if (secondArgument)
293
- hint += DIM_COLOR(", ") + secondArgumentColor(secondArgument);
294
- dimString = ")";
295
- }
296
- if (comment !== "")
297
- dimString += ` // ${comment}`;
298
- if (dimString !== "")
299
- hint += DIM_COLOR(dimString);
300
- return hint;
301
- }
302
- const SPACE_SYMBOL = "\xB7";
303
- const replaceTrailingSpaces = (text) => text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length));
304
- const printReceived = (object) => RECEIVED_COLOR(replaceTrailingSpaces(stringify(object)));
305
- const printExpected = (value) => EXPECTED_COLOR(replaceTrailingSpaces(stringify(value)));
306
- function diff(a, b, options) {
307
- return unifiedDiff(stringify(b), stringify(a));
308
- }
309
- var matcherUtils = /* @__PURE__ */ Object.freeze({
310
- __proto__: null,
311
- stringify,
312
- EXPECTED_COLOR,
313
- RECEIVED_COLOR,
314
- INVERTED_COLOR,
315
- BOLD_WEIGHT,
316
- DIM_COLOR,
317
- matcherHint,
318
- printReceived,
319
- printExpected,
320
- diff
321
- });
322
- function equals(a, b, customTesters, strictCheck) {
323
- customTesters = customTesters || [];
324
- return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey);
325
- }
326
- function isAsymmetric(obj) {
327
- return !!obj && typeof obj === "object" && "asymmetricMatch" in obj && isA("Function", obj.asymmetricMatch);
328
- }
329
- function asymmetricMatch(a, b) {
330
- const asymmetricA = isAsymmetric(a);
331
- const asymmetricB = isAsymmetric(b);
332
- if (asymmetricA && asymmetricB)
333
- return void 0;
334
- if (asymmetricA)
335
- return a.asymmetricMatch(b);
336
- if (asymmetricB)
337
- return b.asymmetricMatch(a);
338
- }
339
- function eq(a, b, aStack, bStack, customTesters, hasKey2) {
340
- let result = true;
341
- const asymmetricResult = asymmetricMatch(a, b);
342
- if (asymmetricResult !== void 0)
343
- return asymmetricResult;
344
- for (let i = 0; i < customTesters.length; i++) {
345
- const customTesterResult = customTesters[i](a, b);
346
- if (customTesterResult !== void 0)
347
- return customTesterResult;
348
- }
349
- if (a instanceof Error && b instanceof Error)
350
- return a.message === b.message;
351
- if (Object.is(a, b))
352
- return true;
353
- if (a === null || b === null)
354
- return a === b;
355
- const className = Object.prototype.toString.call(a);
356
- if (className !== Object.prototype.toString.call(b))
357
- return false;
358
- switch (className) {
359
- case "[object Boolean]":
360
- case "[object String]":
361
- case "[object Number]":
362
- if (typeof a !== typeof b) {
363
- return false;
364
- } else if (typeof a !== "object" && typeof b !== "object") {
365
- return Object.is(a, b);
366
- } else {
367
- return Object.is(a.valueOf(), b.valueOf());
368
- }
369
- case "[object Date]":
370
- return isNaN(a) && isNaN(b) || +a === +b;
371
- case "[object RegExp]":
372
- return a.source === b.source && a.flags === b.flags;
373
- }
374
- if (typeof a !== "object" || typeof b !== "object")
375
- return false;
376
- if (isDomNode(a) && isDomNode(b))
377
- return a.isEqualNode(b);
378
- let length = aStack.length;
379
- while (length--) {
380
- if (aStack[length] === a)
381
- return bStack[length] === b;
382
- else if (bStack[length] === b)
383
- return false;
384
- }
385
- aStack.push(a);
386
- bStack.push(b);
387
- if (className === "[object Array]" && a.length !== b.length)
388
- return false;
389
- const aKeys = keys(a, hasKey2);
390
- let key;
391
- let size = aKeys.length;
392
- if (keys(b, hasKey2).length !== size)
393
- return false;
394
- while (size--) {
395
- key = aKeys[size];
396
- result = hasKey2(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey2);
397
- if (!result)
398
- return false;
399
- }
400
- aStack.pop();
401
- bStack.pop();
402
- return result;
403
- }
404
- function keys(obj, hasKey2) {
405
- const keys2 = [];
406
- for (const key in obj) {
407
- if (hasKey2(obj, key))
408
- keys2.push(key);
409
- }
410
- return keys2.concat(
411
- Object.getOwnPropertySymbols(obj).filter(
412
- (symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable
413
- )
414
- );
415
- }
416
- function hasDefinedKey(obj, key) {
417
- return hasKey(obj, key) && obj[key] !== void 0;
418
- }
419
- function hasKey(obj, key) {
420
- return Object.prototype.hasOwnProperty.call(obj, key);
421
- }
422
- function isA(typeName, value) {
423
- return Object.prototype.toString.apply(value) === `[object ${typeName}]`;
424
- }
425
- function isDomNode(obj) {
426
- return obj !== null && typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string" && typeof obj.isEqualNode === "function";
427
- }
428
- const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@";
429
- const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@";
430
- const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@";
431
- function isImmutableUnorderedKeyed(maybeKeyed) {
432
- return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL] && !maybeKeyed[IS_ORDERED_SENTINEL]);
433
- }
434
- function isImmutableUnorderedSet(maybeSet) {
435
- return !!(maybeSet && maybeSet[IS_SET_SENTINEL] && !maybeSet[IS_ORDERED_SENTINEL]);
436
- }
437
- const IteratorSymbol = Symbol.iterator;
438
- const hasIterator = (object) => !!(object != null && object[IteratorSymbol]);
439
- const iterableEquality = (a, b, aStack = [], bStack = []) => {
440
- if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b))
441
- return void 0;
442
- if (a.constructor !== b.constructor)
443
- return false;
444
- let length = aStack.length;
445
- while (length--) {
446
- if (aStack[length] === a)
447
- return bStack[length] === b;
448
- }
449
- aStack.push(a);
450
- bStack.push(b);
451
- const iterableEqualityWithStack = (a2, b2) => iterableEquality(a2, b2, [...aStack], [...bStack]);
452
- if (a.size !== void 0) {
453
- if (a.size !== b.size) {
454
- return false;
455
- } else if (isA("Set", a) || isImmutableUnorderedSet(a)) {
456
- let allFound = true;
457
- for (const aValue of a) {
458
- if (!b.has(aValue)) {
459
- let has = false;
460
- for (const bValue of b) {
461
- const isEqual = equals(aValue, bValue, [iterableEqualityWithStack]);
462
- if (isEqual === true)
463
- has = true;
464
- }
465
- if (has === false) {
466
- allFound = false;
467
- break;
468
- }
469
- }
470
- }
471
- aStack.pop();
472
- bStack.pop();
473
- return allFound;
474
- } else if (isA("Map", a) || isImmutableUnorderedKeyed(a)) {
475
- let allFound = true;
476
- for (const aEntry of a) {
477
- if (!b.has(aEntry[0]) || !equals(aEntry[1], b.get(aEntry[0]), [iterableEqualityWithStack])) {
478
- let has = false;
479
- for (const bEntry of b) {
480
- const matchedKey = equals(aEntry[0], bEntry[0], [
481
- iterableEqualityWithStack
482
- ]);
483
- let matchedValue = false;
484
- if (matchedKey === true) {
485
- matchedValue = equals(aEntry[1], bEntry[1], [
486
- iterableEqualityWithStack
487
- ]);
488
- }
489
- if (matchedValue === true)
490
- has = true;
491
- }
492
- if (has === false) {
493
- allFound = false;
494
- break;
495
- }
496
- }
497
- }
498
- aStack.pop();
499
- bStack.pop();
500
- return allFound;
501
- }
502
- }
503
- const bIterator = b[IteratorSymbol]();
504
- for (const aValue of a) {
505
- const nextB = bIterator.next();
506
- if (nextB.done || !equals(aValue, nextB.value, [iterableEqualityWithStack]))
507
- return false;
508
- }
509
- if (!bIterator.next().done)
510
- return false;
511
- aStack.pop();
512
- bStack.pop();
513
- return true;
514
- };
515
- const hasPropertyInObject = (object, key) => {
516
- const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype;
517
- if (shouldTerminate)
518
- return false;
519
- return Object.prototype.hasOwnProperty.call(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key);
520
- };
521
- const isObjectWithKeys = (a) => isObject(a) && !(a instanceof Error) && !Array.isArray(a) && !(a instanceof Date);
522
- const subsetEquality = (object, subset) => {
523
- const subsetEqualityWithContext = (seenReferences = /* @__PURE__ */ new WeakMap()) => (object2, subset2) => {
524
- if (!isObjectWithKeys(subset2))
525
- return void 0;
526
- return Object.keys(subset2).every((key) => {
527
- if (isObjectWithKeys(subset2[key])) {
528
- if (seenReferences.has(subset2[key]))
529
- return equals(object2[key], subset2[key], [iterableEquality]);
530
- seenReferences.set(subset2[key], true);
531
- }
532
- const result = object2 != null && hasPropertyInObject(object2, key) && equals(object2[key], subset2[key], [
533
- iterableEquality,
534
- subsetEqualityWithContext(seenReferences)
535
- ]);
536
- seenReferences.delete(subset2[key]);
537
- return result;
538
- });
539
- };
540
- return subsetEqualityWithContext()(object, subset);
541
- };
542
- const typeEquality = (a, b) => {
543
- if (a == null || b == null || a.constructor === b.constructor)
544
- return void 0;
545
- return false;
546
- };
547
- const arrayBufferEquality = (a, b) => {
548
- if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer))
549
- return void 0;
550
- const dataViewA = new DataView(a);
551
- const dataViewB = new DataView(b);
552
- if (dataViewA.byteLength !== dataViewB.byteLength)
553
- return false;
554
- for (let i = 0; i < dataViewA.byteLength; i++) {
555
- if (dataViewA.getUint8(i) !== dataViewB.getUint8(i))
556
- return false;
557
- }
558
- return true;
559
- };
560
- const sparseArrayEquality = (a, b) => {
561
- if (!Array.isArray(a) || !Array.isArray(b))
562
- return void 0;
563
- const aKeys = Object.keys(a);
564
- const bKeys = Object.keys(b);
565
- return equals(a, b, [iterableEquality, typeEquality], true) && equals(aKeys, bKeys);
566
- };
567
- const generateToBeMessage = (deepEqualityName, expected = "#{this}", actual = "#{exp}") => {
568
- const toBeMessage = `expected ${expected} to be ${actual} // Object.is equality`;
569
- if (["toStrictEqual", "toEqual"].includes(deepEqualityName))
570
- return `${toBeMessage}
571
-
572
- If it should pass with deep equality, replace "toBe" with "${deepEqualityName}"
573
-
574
- Expected: ${expected}
575
- Received: serializes to the same string
576
- `;
577
- return toBeMessage;
578
- };
579
- class AsymmetricMatcher$1 {
580
- constructor(sample, inverse = false) {
581
- this.sample = sample;
582
- this.inverse = inverse;
583
- this.$$typeof = Symbol.for("jest.asymmetricMatcher");
584
- }
585
- getMatcherContext(expect) {
586
- return {
587
- ...getState(expect || globalThis[GLOBAL_EXPECT]),
588
- equals,
589
- isNot: this.inverse,
590
- utils: matcherUtils
591
- };
592
- }
593
- }
594
- class StringContaining extends AsymmetricMatcher$1 {
595
- constructor(sample, inverse = false) {
596
- if (!isA("String", sample))
597
- throw new Error("Expected is not a string");
598
- super(sample, inverse);
599
- }
600
- asymmetricMatch(other) {
601
- const result = isA("String", other) && other.includes(this.sample);
602
- return this.inverse ? !result : result;
603
- }
604
- toString() {
605
- return `String${this.inverse ? "Not" : ""}Containing`;
606
- }
607
- getExpectedType() {
608
- return "string";
609
- }
610
- }
611
- class Anything extends AsymmetricMatcher$1 {
612
- asymmetricMatch(other) {
613
- return other != null;
614
- }
615
- toString() {
616
- return "Anything";
617
- }
618
- toAsymmetricMatcher() {
619
- return "Anything";
620
- }
621
- }
622
- class ObjectContaining extends AsymmetricMatcher$1 {
623
- constructor(sample, inverse = false) {
624
- super(sample, inverse);
625
- }
626
- getPrototype(obj) {
627
- if (Object.getPrototypeOf)
628
- return Object.getPrototypeOf(obj);
629
- if (obj.constructor.prototype === obj)
630
- return null;
631
- return obj.constructor.prototype;
632
- }
633
- hasProperty(obj, property) {
634
- if (!obj)
635
- return false;
636
- if (Object.prototype.hasOwnProperty.call(obj, property))
637
- return true;
638
- return this.hasProperty(this.getPrototype(obj), property);
639
- }
640
- asymmetricMatch(other) {
641
- if (typeof this.sample !== "object") {
642
- throw new TypeError(
643
- `You must provide an object to ${this.toString()}, not '${typeof this.sample}'.`
644
- );
645
- }
646
- let result = true;
647
- for (const property in this.sample) {
648
- if (!this.hasProperty(other, property) || !equals(this.sample[property], other[property])) {
649
- result = false;
650
- break;
651
- }
652
- }
653
- return this.inverse ? !result : result;
654
- }
655
- toString() {
656
- return `Object${this.inverse ? "Not" : ""}Containing`;
657
- }
658
- getExpectedType() {
659
- return "object";
660
- }
661
- }
662
- class ArrayContaining extends AsymmetricMatcher$1 {
663
- constructor(sample, inverse = false) {
664
- super(sample, inverse);
665
- }
666
- asymmetricMatch(other) {
667
- if (!Array.isArray(this.sample)) {
668
- throw new TypeError(
669
- `You must provide an array to ${this.toString()}, not '${typeof this.sample}'.`
670
- );
671
- }
672
- const result = this.sample.length === 0 || Array.isArray(other) && this.sample.every(
673
- (item) => other.some((another) => equals(item, another))
674
- );
675
- return this.inverse ? !result : result;
676
- }
677
- toString() {
678
- return `Array${this.inverse ? "Not" : ""}Containing`;
679
- }
680
- getExpectedType() {
681
- return "array";
682
- }
683
- }
684
- class Any extends AsymmetricMatcher$1 {
685
- constructor(sample) {
686
- if (typeof sample === "undefined") {
687
- throw new TypeError(
688
- "any() expects to be passed a constructor function. Please pass one or use anything() to match any object."
689
- );
690
- }
691
- super(sample);
692
- }
693
- fnNameFor(func) {
694
- if (func.name)
695
- return func.name;
696
- const functionToString2 = Function.prototype.toString;
697
- const matches = functionToString2.call(func).match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/);
698
- return matches ? matches[1] : "<anonymous>";
699
- }
700
- asymmetricMatch(other) {
701
- if (this.sample === String)
702
- return typeof other == "string" || other instanceof String;
703
- if (this.sample === Number)
704
- return typeof other == "number" || other instanceof Number;
705
- if (this.sample === Function)
706
- return typeof other == "function" || other instanceof Function;
707
- if (this.sample === Boolean)
708
- return typeof other == "boolean" || other instanceof Boolean;
709
- if (this.sample === BigInt)
710
- return typeof other == "bigint" || other instanceof BigInt;
711
- if (this.sample === Symbol)
712
- return typeof other == "symbol" || other instanceof Symbol;
713
- if (this.sample === Object)
714
- return typeof other == "object";
715
- return other instanceof this.sample;
716
- }
717
- toString() {
718
- return "Any";
719
- }
720
- getExpectedType() {
721
- if (this.sample === String)
722
- return "string";
723
- if (this.sample === Number)
724
- return "number";
725
- if (this.sample === Function)
726
- return "function";
727
- if (this.sample === Object)
728
- return "object";
729
- if (this.sample === Boolean)
730
- return "boolean";
731
- return this.fnNameFor(this.sample);
732
- }
733
- toAsymmetricMatcher() {
734
- return `Any<${this.fnNameFor(this.sample)}>`;
735
- }
736
- }
737
- class StringMatching extends AsymmetricMatcher$1 {
738
- constructor(sample, inverse = false) {
739
- if (!isA("String", sample) && !isA("RegExp", sample))
740
- throw new Error("Expected is not a String or a RegExp");
741
- super(new RegExp(sample), inverse);
742
- }
743
- asymmetricMatch(other) {
744
- const result = isA("String", other) && this.sample.test(other);
745
- return this.inverse ? !result : result;
746
- }
747
- toString() {
748
- return `String${this.inverse ? "Not" : ""}Matching`;
749
- }
750
- getExpectedType() {
751
- return "string";
752
- }
753
- }
754
- const JestAsymmetricMatchers = (chai, utils) => {
755
- utils.addMethod(
756
- chai.expect,
757
- "anything",
758
- () => new Anything()
759
- );
760
- utils.addMethod(
761
- chai.expect,
762
- "any",
763
- (expected) => new Any(expected)
764
- );
765
- utils.addMethod(
766
- chai.expect,
767
- "stringContaining",
768
- (expected) => new StringContaining(expected)
769
- );
770
- utils.addMethod(
771
- chai.expect,
772
- "objectContaining",
773
- (expected) => new ObjectContaining(expected)
774
- );
775
- utils.addMethod(
776
- chai.expect,
777
- "arrayContaining",
778
- (expected) => new ArrayContaining(expected)
779
- );
780
- utils.addMethod(
781
- chai.expect,
782
- "stringMatching",
783
- (expected) => new StringMatching(expected)
784
- );
785
- chai.expect.not = {
786
- stringContaining: (expected) => new StringContaining(expected, true),
787
- objectContaining: (expected) => new ObjectContaining(expected, true),
788
- arrayContaining: (expected) => new ArrayContaining(expected, true),
789
- stringMatching: (expected) => new StringMatching(expected, true)
790
- };
791
- };
792
- const JestChaiExpect = (chai, utils) => {
793
- function def(name, fn) {
794
- const addMethod = (n) => {
795
- utils.addMethod(chai.Assertion.prototype, n, fn);
796
- utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, n, fn);
797
- };
798
- if (Array.isArray(name))
799
- name.forEach((n) => addMethod(n));
800
- else
801
- addMethod(name);
802
- }
803
- ["throw", "throws", "Throw"].forEach((m) => {
804
- utils.overwriteMethod(chai.Assertion.prototype, m, (_super) => {
805
- return function(...args) {
806
- const promise = utils.flag(this, "promise");
807
- const object = utils.flag(this, "object");
808
- const isNot = utils.flag(this, "negate");
809
- if (promise === "rejects") {
810
- utils.flag(this, "object", () => {
811
- throw object;
812
- });
813
- } else if (promise === "resolves" && typeof object !== "function") {
814
- if (!isNot) {
815
- const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't";
816
- const error = {
817
- showDiff: false
818
- };
819
- throw new AssertionError(message, error, utils.flag(this, "ssfi"));
820
- } else {
821
- return;
822
- }
823
- }
824
- _super.apply(this, args);
825
- };
826
- });
827
- });
828
- def("withTest", function(test) {
829
- utils.flag(this, "vitest-test", test);
830
- return this;
831
- });
832
- def("toEqual", function(expected) {
833
- const actual = utils.flag(this, "object");
834
- const equal = equals(
835
- actual,
836
- expected,
837
- [iterableEquality]
838
- );
839
- return this.assert(
840
- equal,
841
- "expected #{this} to deeply equal #{exp}",
842
- "expected #{this} to not deeply equal #{exp}",
843
- expected,
844
- actual
845
- );
846
- });
847
- def("toStrictEqual", function(expected) {
848
- const obj = utils.flag(this, "object");
849
- const equal = equals(
850
- obj,
851
- expected,
852
- [
853
- iterableEquality,
854
- typeEquality,
855
- sparseArrayEquality,
856
- arrayBufferEquality
857
- ],
858
- true
859
- );
860
- return this.assert(
861
- equal,
862
- "expected #{this} to strictly equal #{exp}",
863
- "expected #{this} to not strictly equal #{exp}",
864
- expected,
865
- obj
866
- );
867
- });
868
- def("toBe", function(expected) {
869
- const actual = this._obj;
870
- const pass = Object.is(actual, expected);
871
- let deepEqualityName = "";
872
- if (!pass) {
873
- const toStrictEqualPass = equals(
874
- actual,
875
- expected,
876
- [
877
- iterableEquality,
878
- typeEquality,
879
- sparseArrayEquality,
880
- arrayBufferEquality
881
- ],
882
- true
883
- );
884
- if (toStrictEqualPass) {
885
- deepEqualityName = "toStrictEqual";
886
- } else {
887
- const toEqualPass = equals(
888
- actual,
889
- expected,
890
- [iterableEquality]
891
- );
892
- if (toEqualPass)
893
- deepEqualityName = "toEqual";
894
- }
895
- }
896
- return this.assert(
897
- pass,
898
- generateToBeMessage(deepEqualityName),
899
- "expected #{this} not to be #{exp} // Object.is equality",
900
- expected,
901
- actual
902
- );
903
- });
904
- def("toMatchObject", function(expected) {
905
- const actual = this._obj;
906
- return this.assert(
907
- equals(actual, expected, [iterableEquality, subsetEquality]),
908
- "expected #{this} to match object #{exp}",
909
- "expected #{this} to not match object #{exp}",
910
- expected,
911
- actual
912
- );
913
- });
914
- def("toMatch", function(expected) {
915
- if (typeof expected === "string")
916
- return this.include(expected);
917
- else
918
- return this.match(expected);
919
- });
920
- def("toContain", function(item) {
921
- return this.contain(item);
922
- });
923
- def("toContainEqual", function(expected) {
924
- const obj = utils.flag(this, "object");
925
- const index = Array.from(obj).findIndex((item) => {
926
- return equals(item, expected);
927
- });
928
- this.assert(
929
- index !== -1,
930
- "expected #{this} to deep equally contain #{exp}",
931
- "expected #{this} to not deep equally contain #{exp}",
932
- expected
933
- );
934
- });
935
- def("toBeTruthy", function() {
936
- const obj = utils.flag(this, "object");
937
- this.assert(
938
- Boolean(obj),
939
- "expected #{this} to be truthy",
940
- "expected #{this} to not be truthy",
941
- obj
942
- );
943
- });
944
- def("toBeFalsy", function() {
945
- const obj = utils.flag(this, "object");
946
- this.assert(
947
- !obj,
948
- "expected #{this} to be falsy",
949
- "expected #{this} to not be falsy",
950
- obj
951
- );
952
- });
953
- def("toBeGreaterThan", function(expected) {
954
- const actual = this._obj;
955
- assertTypes(actual, "actual", ["number", "bigint"]);
956
- assertTypes(expected, "expected", ["number", "bigint"]);
957
- return this.assert(
958
- actual > expected,
959
- `expected ${actual} to be greater than ${expected}`,
960
- `expected ${actual} to be not greater than ${expected}`,
961
- actual,
962
- expected
963
- );
964
- });
965
- def("toBeGreaterThanOrEqual", function(expected) {
966
- const actual = this._obj;
967
- assertTypes(actual, "actual", ["number", "bigint"]);
968
- assertTypes(expected, "expected", ["number", "bigint"]);
969
- return this.assert(
970
- actual >= expected,
971
- `expected ${actual} to be greater than or equal to ${expected}`,
972
- `expected ${actual} to be not greater than or equal to ${expected}`,
973
- actual,
974
- expected
975
- );
976
- });
977
- def("toBeLessThan", function(expected) {
978
- const actual = this._obj;
979
- assertTypes(actual, "actual", ["number", "bigint"]);
980
- assertTypes(expected, "expected", ["number", "bigint"]);
981
- return this.assert(
982
- actual < expected,
983
- `expected ${actual} to be less than ${expected}`,
984
- `expected ${actual} to be not less than ${expected}`,
985
- actual,
986
- expected
987
- );
988
- });
989
- def("toBeLessThanOrEqual", function(expected) {
990
- const actual = this._obj;
991
- assertTypes(actual, "actual", ["number", "bigint"]);
992
- assertTypes(expected, "expected", ["number", "bigint"]);
993
- return this.assert(
994
- actual <= expected,
995
- `expected ${actual} to be less than or equal to ${expected}`,
996
- `expected ${actual} to be not less than or equal to ${expected}`,
997
- actual,
998
- expected
999
- );
1000
- });
1001
- def("toBeNaN", function() {
1002
- return this.be.NaN;
1003
- });
1004
- def("toBeUndefined", function() {
1005
- return this.be.undefined;
1006
- });
1007
- def("toBeNull", function() {
1008
- return this.be.null;
1009
- });
1010
- def("toBeDefined", function() {
1011
- const negate = utils.flag(this, "negate");
1012
- utils.flag(this, "negate", false);
1013
- if (negate)
1014
- return this.be.undefined;
1015
- return this.not.be.undefined;
1016
- });
1017
- def("toBeTypeOf", function(expected) {
1018
- const actual = typeof this._obj;
1019
- const equal = expected === actual;
1020
- return this.assert(
1021
- equal,
1022
- "expected #{this} to be type of #{exp}",
1023
- "expected #{this} not to be type of #{exp}",
1024
- expected,
1025
- actual
1026
- );
1027
- });
1028
- def("toBeInstanceOf", function(obj) {
1029
- return this.instanceOf(obj);
1030
- });
1031
- def("toHaveLength", function(length) {
1032
- return this.have.length(length);
1033
- });
1034
- def("toHaveProperty", function(...args) {
1035
- if (Array.isArray(args[0]))
1036
- args[0] = args[0].map((key) => key.replace(/([.[\]])/g, "\\$1")).join(".");
1037
- const actual = this._obj;
1038
- const [propertyName, expected] = args;
1039
- const getValue = () => {
1040
- const hasOwn = Object.prototype.hasOwnProperty.call(actual, propertyName);
1041
- if (hasOwn)
1042
- return { value: actual[propertyName], exists: true };
1043
- return utils.getPathInfo(actual, propertyName);
1044
- };
1045
- const { value, exists } = getValue();
1046
- const pass = exists && (args.length === 1 || equals(expected, value));
1047
- const valueString = args.length === 1 ? "" : ` with value ${utils.objDisplay(expected)}`;
1048
- return this.assert(
1049
- pass,
1050
- `expected #{this} to have property "${propertyName}"${valueString}`,
1051
- `expected #{this} to not have property "${propertyName}"${valueString}`,
1052
- actual
1053
- );
1054
- });
1055
- def("toBeCloseTo", function(received, precision = 2) {
1056
- const expected = this._obj;
1057
- let pass = false;
1058
- let expectedDiff = 0;
1059
- let receivedDiff = 0;
1060
- if (received === Infinity && expected === Infinity) {
1061
- pass = true;
1062
- } else if (received === -Infinity && expected === -Infinity) {
1063
- pass = true;
1064
- } else {
1065
- expectedDiff = 10 ** -precision / 2;
1066
- receivedDiff = Math.abs(expected - received);
1067
- pass = receivedDiff < expectedDiff;
1068
- }
1069
- return this.assert(
1070
- pass,
1071
- `expected #{this} to be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`,
1072
- `expected #{this} to not be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`,
1073
- received,
1074
- expected
1075
- );
1076
- });
1077
- const assertIsMock = (assertion) => {
1078
- if (!isMockFunction(assertion._obj))
1079
- throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`);
1080
- };
1081
- const getSpy = (assertion) => {
1082
- assertIsMock(assertion);
1083
- return assertion._obj;
1084
- };
1085
- const ordinalOf = (i) => {
1086
- const j = i % 10;
1087
- const k = i % 100;
1088
- if (j === 1 && k !== 11)
1089
- return `${i}st`;
1090
- if (j === 2 && k !== 12)
1091
- return `${i}nd`;
1092
- if (j === 3 && k !== 13)
1093
- return `${i}rd`;
1094
- return `${i}th`;
1095
- };
1096
- const formatCalls = (spy, msg, actualCall) => {
1097
- msg += c.gray(`
1098
-
1099
- Received:
1100
- ${spy.mock.calls.map((callArg, i) => {
1101
- let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call:
1102
-
1103
- `);
1104
- if (actualCall)
1105
- methodCall += unifiedDiff(stringify(callArg), stringify(actualCall), { showLegend: false });
1106
- else
1107
- methodCall += stringify(callArg).split("\n").map((line) => ` ${line}`).join("\n");
1108
- methodCall += "\n";
1109
- return methodCall;
1110
- }).join("\n")}`);
1111
- msg += c.gray(`
1112
-
1113
- Number of calls: ${c.bold(spy.mock.calls.length)}
1114
- `);
1115
- return msg;
1116
- };
1117
- const formatReturns = (spy, msg, actualReturn) => {
1118
- msg += c.gray(`
1119
-
1120
- Received:
1121
- ${spy.mock.results.map((callReturn, i) => {
1122
- let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call return:
1123
-
1124
- `);
1125
- if (actualReturn)
1126
- methodCall += unifiedDiff(stringify(callReturn.value), stringify(actualReturn), { showLegend: false });
1127
- else
1128
- methodCall += stringify(callReturn).split("\n").map((line) => ` ${line}`).join("\n");
1129
- methodCall += "\n";
1130
- return methodCall;
1131
- }).join("\n")}`);
1132
- msg += c.gray(`
1133
-
1134
- Number of calls: ${c.bold(spy.mock.calls.length)}
1135
- `);
1136
- return msg;
1137
- };
1138
- def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) {
1139
- const spy = getSpy(this);
1140
- const spyName = spy.getMockName();
1141
- const callCount = spy.mock.calls.length;
1142
- return this.assert(
1143
- callCount === number,
1144
- `expected "${spyName}" to be called #{exp} times`,
1145
- `expected "${spyName}" to not be called #{exp} times`,
1146
- number,
1147
- callCount
1148
- );
1149
- });
1150
- def("toHaveBeenCalledOnce", function() {
1151
- const spy = getSpy(this);
1152
- const spyName = spy.getMockName();
1153
- const callCount = spy.mock.calls.length;
1154
- return this.assert(
1155
- callCount === 1,
1156
- `expected "${spyName}" to be called once`,
1157
- `expected "${spyName}" to not be called once`,
1158
- 1,
1159
- callCount
1160
- );
1161
- });
1162
- def(["toHaveBeenCalled", "toBeCalled"], function() {
1163
- const spy = getSpy(this);
1164
- const spyName = spy.getMockName();
1165
- const called = spy.mock.calls.length > 0;
1166
- const isNot = utils.flag(this, "negate");
1167
- let msg = utils.getMessage(
1168
- this,
1169
- [
1170
- called,
1171
- `expected "${spyName}" to be called at least once`,
1172
- `expected "${spyName}" to not be called at all`,
1173
- true,
1174
- called
1175
- ]
1176
- );
1177
- if (called && isNot)
1178
- msg = formatCalls(spy, msg);
1179
- if (called && isNot || !called && !isNot) {
1180
- const err = new Error(msg);
1181
- err.name = "AssertionError";
1182
- throw err;
1183
- }
1184
- });
1185
- def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) {
1186
- const spy = getSpy(this);
1187
- const spyName = spy.getMockName();
1188
- const pass = spy.mock.calls.some((callArg) => equals(callArg, args, [iterableEquality]));
1189
- const isNot = utils.flag(this, "negate");
1190
- let msg = utils.getMessage(
1191
- this,
1192
- [
1193
- pass,
1194
- `expected "${spyName}" to be called with arguments: #{exp}`,
1195
- `expected "${spyName}" to not be called with arguments: #{exp}`,
1196
- args
1197
- ]
1198
- );
1199
- if (pass && isNot || !pass && !isNot) {
1200
- msg = formatCalls(spy, msg, args);
1201
- const err = new Error(msg);
1202
- err.name = "AssertionError";
1203
- throw err;
1204
- }
1205
- });
1206
- def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) {
1207
- const spy = getSpy(this);
1208
- const spyName = spy.getMockName();
1209
- const nthCall = spy.mock.calls[times - 1];
1210
- this.assert(
1211
- equals(nthCall, args, [iterableEquality]),
1212
- `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}`,
1213
- `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`,
1214
- args,
1215
- nthCall
1216
- );
1217
- });
1218
- def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) {
1219
- const spy = getSpy(this);
1220
- const spyName = spy.getMockName();
1221
- const lastCall = spy.mock.calls[spy.calls.length - 1];
1222
- this.assert(
1223
- equals(lastCall, args, [iterableEquality]),
1224
- `expected last "${spyName}" call to have been called with #{exp}`,
1225
- `expected last "${spyName}" call to not have been called with #{exp}`,
1226
- args,
1227
- lastCall
1228
- );
1229
- });
1230
- def(["toThrow", "toThrowError"], function(expected) {
1231
- if (typeof expected === "string" || typeof expected === "undefined" || expected instanceof RegExp)
1232
- return this.throws(expected);
1233
- const obj = this._obj;
1234
- const promise = utils.flag(this, "promise");
1235
- const isNot = utils.flag(this, "negate");
1236
- let thrown = null;
1237
- if (promise === "rejects") {
1238
- thrown = obj;
1239
- } else if (promise === "resolves" && typeof obj !== "function") {
1240
- if (!isNot) {
1241
- const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't";
1242
- const error = {
1243
- showDiff: false
1244
- };
1245
- throw new AssertionError(message, error, utils.flag(this, "ssfi"));
1246
- } else {
1247
- return;
1248
- }
1249
- } else {
1250
- try {
1251
- obj();
1252
- } catch (err) {
1253
- thrown = err;
1254
- }
1255
- }
1256
- if (typeof expected === "function") {
1257
- const name = expected.name || expected.prototype.constructor.name;
1258
- return this.assert(
1259
- thrown && thrown instanceof expected,
1260
- `expected error to be instance of ${name}`,
1261
- `expected error not to be instance of ${name}`,
1262
- expected,
1263
- thrown
1264
- );
1265
- }
1266
- if (expected instanceof Error) {
1267
- return this.assert(
1268
- thrown && expected.message === thrown.message,
1269
- `expected error to have message: ${expected.message}`,
1270
- `expected error not to have message: ${expected.message}`,
1271
- expected.message,
1272
- thrown && thrown.message
1273
- );
1274
- }
1275
- if (typeof expected === "object" && "asymmetricMatch" in expected && typeof expected.asymmetricMatch === "function") {
1276
- const matcher = expected;
1277
- return this.assert(
1278
- thrown && matcher.asymmetricMatch(thrown),
1279
- "expected error to match asymmetric matcher",
1280
- "expected error not to match asymmetric matcher",
1281
- matcher.toString(),
1282
- thrown
1283
- );
1284
- }
1285
- throw new Error(`"toThrow" expects string, RegExp, function, Error instance or asymmetric matcher, got "${typeof expected}"`);
1286
- });
1287
- def(["toHaveReturned", "toReturn"], function() {
1288
- const spy = getSpy(this);
1289
- const spyName = spy.getMockName();
1290
- const calledAndNotThrew = spy.mock.calls.length > 0 && !spy.mock.results.some(({ type }) => type === "throw");
1291
- this.assert(
1292
- calledAndNotThrew,
1293
- `expected "${spyName}" to be successfully called at least once`,
1294
- `expected "${spyName}" to not be successfully called`,
1295
- calledAndNotThrew,
1296
- !calledAndNotThrew
1297
- );
1298
- });
1299
- def(["toHaveReturnedTimes", "toReturnTimes"], function(times) {
1300
- const spy = getSpy(this);
1301
- const spyName = spy.getMockName();
1302
- const successfulReturns = spy.mock.results.reduce((success, { type }) => type === "throw" ? success : ++success, 0);
1303
- this.assert(
1304
- successfulReturns === times,
1305
- `expected "${spyName}" to be successfully called ${times} times`,
1306
- `expected "${spyName}" to not be successfully called ${times} times`,
1307
- `expected number of returns: ${times}`,
1308
- `received number of returns: ${successfulReturns}`
1309
- );
1310
- });
1311
- def(["toHaveReturnedWith", "toReturnWith"], function(value) {
1312
- const spy = getSpy(this);
1313
- const spyName = spy.getMockName();
1314
- const pass = spy.mock.results.some(({ type, value: result }) => type === "return" && equals(value, result));
1315
- const isNot = utils.flag(this, "negate");
1316
- let msg = utils.getMessage(
1317
- this,
1318
- [
1319
- pass,
1320
- `expected "${spyName}" to return with: #{exp} at least once`,
1321
- `expected "${spyName}" to not return with: #{exp}`,
1322
- value
1323
- ]
1324
- );
1325
- if (pass && isNot || !pass && !isNot) {
1326
- msg = formatReturns(spy, msg, value);
1327
- const err = new Error(msg);
1328
- err.name = "AssertionError";
1329
- throw err;
1330
- }
1331
- });
1332
- def(["toHaveLastReturnedWith", "lastReturnedWith"], function(value) {
1333
- const spy = getSpy(this);
1334
- const spyName = spy.getMockName();
1335
- const { value: lastResult } = spy.mock.results[spy.returns.length - 1];
1336
- const pass = equals(lastResult, value);
1337
- this.assert(
1338
- pass,
1339
- `expected last "${spyName}" call to return #{exp}`,
1340
- `expected last "${spyName}" call to not return #{exp}`,
1341
- value,
1342
- lastResult
1343
- );
1344
- });
1345
- def(["toHaveNthReturnedWith", "nthReturnedWith"], function(nthCall, value) {
1346
- const spy = getSpy(this);
1347
- const spyName = spy.getMockName();
1348
- const isNot = utils.flag(this, "negate");
1349
- const { type: callType, value: callResult } = spy.mock.results[nthCall - 1];
1350
- const ordinalCall = `${ordinalOf(nthCall)} call`;
1351
- if (!isNot && callType === "throw")
1352
- chai.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`);
1353
- const nthCallReturn = equals(callResult, value);
1354
- this.assert(
1355
- nthCallReturn,
1356
- `expected ${ordinalCall} "${spyName}" call to return #{exp}`,
1357
- `expected ${ordinalCall} "${spyName}" call to not return #{exp}`,
1358
- value,
1359
- callResult
1360
- );
1361
- });
1362
- def("toSatisfy", function(matcher, message) {
1363
- return this.be.satisfy(matcher, message);
1364
- });
1365
- utils.addProperty(chai.Assertion.prototype, "resolves", function __VITEST_RESOLVES__() {
1366
- utils.flag(this, "promise", "resolves");
1367
- utils.flag(this, "error", new Error("resolves"));
1368
- const obj = utils.flag(this, "object");
1369
- if (typeof (obj == null ? void 0 : obj.then) !== "function")
1370
- throw new TypeError(`You must provide a Promise to expect() when using .resolves, not '${typeof obj}'.`);
1371
- const proxy = new Proxy(this, {
1372
- get: (target, key, receiver) => {
1373
- const result = Reflect.get(target, key, receiver);
1374
- if (typeof result !== "function")
1375
- return result instanceof chai.Assertion ? proxy : result;
1376
- return async (...args) => {
1377
- return obj.then(
1378
- (value) => {
1379
- utils.flag(this, "object", value);
1380
- return result.call(this, ...args);
1381
- },
1382
- (err) => {
1383
- throw new Error(`promise rejected "${String(err)}" instead of resolving`);
1384
- }
1385
- );
1386
- };
1387
- }
1388
- });
1389
- return proxy;
1390
- });
1391
- utils.addProperty(chai.Assertion.prototype, "rejects", function __VITEST_REJECTS__() {
1392
- utils.flag(this, "promise", "rejects");
1393
- utils.flag(this, "error", new Error("rejects"));
1394
- const obj = utils.flag(this, "object");
1395
- const wrapper = typeof obj === "function" ? obj() : obj;
1396
- if (typeof (wrapper == null ? void 0 : wrapper.then) !== "function")
1397
- throw new TypeError(`You must provide a Promise to expect() when using .rejects, not '${typeof wrapper}'.`);
1398
- const proxy = new Proxy(this, {
1399
- get: (target, key, receiver) => {
1400
- const result = Reflect.get(target, key, receiver);
1401
- if (typeof result !== "function")
1402
- return result instanceof chai.Assertion ? proxy : result;
1403
- return async (...args) => {
1404
- return wrapper.then(
1405
- (value) => {
1406
- throw new Error(`promise resolved "${String(value)}" instead of rejecting`);
1407
- },
1408
- (err) => {
1409
- utils.flag(this, "object", err);
1410
- return result.call(this, ...args);
1411
- }
1412
- );
1413
- };
1414
- }
1415
- });
1416
- return proxy;
1417
- });
1418
- };
1419
- const isAsyncFunction = (fn) => typeof fn === "function" && fn[Symbol.toStringTag] === "AsyncFunction";
1420
- const getMatcherState = (assertion, expect) => {
1421
- const obj = assertion._obj;
1422
- const isNot = util.flag(assertion, "negate");
1423
- const promise = util.flag(assertion, "promise") || "";
1424
- const jestUtils = {
1425
- ...matcherUtils,
1426
- iterableEquality,
1427
- subsetEquality
1428
- };
1429
- const matcherState = {
1430
- ...getState(expect),
1431
- isNot,
1432
- utils: jestUtils,
1433
- promise,
1434
- equals,
1435
- suppressedErrors: []
1436
- };
1437
- return {
1438
- state: matcherState,
1439
- isNot,
1440
- obj
1441
- };
1442
- };
1443
- class JestExtendError extends Error {
1444
- constructor(message, actual, expected) {
1445
- super(message);
1446
- this.actual = actual;
1447
- this.expected = expected;
1448
- }
1449
- }
1450
- function JestExtendPlugin(expect, matchers) {
1451
- return (c2, utils) => {
1452
- Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => {
1453
- function expectSyncWrapper(...args) {
1454
- const { state, isNot, obj } = getMatcherState(this, expect);
1455
- const { pass, message, actual, expected } = expectAssertion.call(state, obj, ...args);
1456
- if (pass && isNot || !pass && !isNot)
1457
- throw new JestExtendError(message(), actual, expected);
1458
- }
1459
- async function expectAsyncWrapper(...args) {
1460
- const { state, isNot, obj } = getMatcherState(this, expect);
1461
- const { pass, message, actual, expected } = await expectAssertion.call(state, obj, ...args);
1462
- if (pass && isNot || !pass && !isNot)
1463
- throw new JestExtendError(message(), actual, expected);
1464
- }
1465
- const expectAssertionWrapper = isAsyncFunction(expectAssertion) ? expectAsyncWrapper : expectSyncWrapper;
1466
- utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, expectAssertionName, expectAssertionWrapper);
1467
- utils.addMethod(c2.Assertion.prototype, expectAssertionName, expectAssertionWrapper);
1468
- class CustomMatcher extends AsymmetricMatcher$1 {
1469
- constructor(inverse = false, ...sample) {
1470
- super(sample, inverse);
1471
- }
1472
- asymmetricMatch(other) {
1473
- const { pass } = expectAssertion.call(
1474
- this.getMatcherContext(expect),
1475
- other,
1476
- ...this.sample
1477
- );
1478
- return this.inverse ? !pass : pass;
1479
- }
1480
- toString() {
1481
- return `${this.inverse ? "not." : ""}${expectAssertionName}`;
1482
- }
1483
- getExpectedType() {
1484
- return "any";
1485
- }
1486
- toAsymmetricMatcher() {
1487
- return `${this.toString()}<${this.sample.map(String).join(", ")}>`;
1488
- }
1489
- }
1490
- Object.defineProperty(expect, expectAssertionName, {
1491
- configurable: true,
1492
- enumerable: true,
1493
- value: (...sample) => new CustomMatcher(false, ...sample),
1494
- writable: true
1495
- });
1496
- Object.defineProperty(expect.not, expectAssertionName, {
1497
- configurable: true,
1498
- enumerable: true,
1499
- value: (...sample) => new CustomMatcher(true, ...sample),
1500
- writable: true
1501
- });
1502
- });
1503
- };
1504
- }
1505
- const JestExtend = (chai, utils) => {
1506
- utils.addMethod(chai.expect, "extend", (expect, expects) => {
1507
- chai.use(JestExtendPlugin(expect, expects));
1508
- });
1509
- };
1510
-
1511
- var naturalCompare$1 = {exports: {}};
1512
-
1513
- /*
1514
- * @version 1.4.0
1515
- * @date 2015-10-26
1516
- * @stability 3 - Stable
1517
- * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
1518
- * @license MIT License
1519
- */
1520
-
1521
-
1522
- var naturalCompare = function(a, b) {
1523
- var i, codeA
1524
- , codeB = 1
1525
- , posA = 0
1526
- , posB = 0
1527
- , alphabet = String.alphabet;
1528
-
1529
- function getCode(str, pos, code) {
1530
- if (code) {
1531
- for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
1532
- return +str.slice(pos - 1, i)
1533
- }
1534
- code = alphabet && alphabet.indexOf(str.charAt(pos));
1535
- return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code
1536
- : code < 46 ? 65 // -
1537
- : code < 48 ? code - 1
1538
- : code < 58 ? code + 18 // 0-9
1539
- : code < 65 ? code - 11
1540
- : code < 91 ? code + 11 // A-Z
1541
- : code < 97 ? code - 37
1542
- : code < 123 ? code + 5 // a-z
1543
- : code - 63
1544
- }
1545
-
1546
-
1547
- if ((a+="") != (b+="")) for (;codeB;) {
1548
- codeA = getCode(a, posA++);
1549
- codeB = getCode(b, posB++);
1550
-
1551
- if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) {
1552
- codeA = getCode(a, posA, posA);
1553
- codeB = getCode(b, posB, posA = i);
1554
- posB = i;
1555
- }
1556
-
1557
- if (codeA != codeB) return (codeA < codeB) ? -1 : 1
1558
- }
1559
- return 0
1560
- };
1561
-
1562
- try {
1563
- naturalCompare$1.exports = naturalCompare;
1564
- } catch (e) {
1565
- String.naturalCompare = naturalCompare;
1566
- }
1567
-
1568
- const serialize$1 = (val, config, indentation, depth, refs, printer) => {
1569
- const name = val.getMockName();
1570
- const nameString = name === "vi.fn()" ? "" : ` ${name}`;
1571
- let callsString = "";
1572
- if (val.mock.calls.length !== 0) {
1573
- const indentationNext = indentation + config.indent;
1574
- callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer(val.mock.calls, config, indentationNext, depth, refs)}${config.min ? ", " : ","}${config.spacingOuter}${indentationNext}"results": ${printer(val.mock.results, config, indentationNext, depth, refs)}${config.min ? "" : ","}${config.spacingOuter}${indentation}}`;
1575
- }
1576
- return `[MockFunction${nameString}]${callsString}`;
1577
- };
1578
- const test$1 = (val) => val && !!val._isMockFunction;
1579
- const plugin = { serialize: serialize$1, test: test$1 };
1580
-
1581
- const {
1582
- DOMCollection,
1583
- DOMElement,
1584
- Immutable,
1585
- ReactElement,
1586
- ReactTestComponent,
1587
- AsymmetricMatcher
1588
- } = plugins_1;
1589
- let PLUGINS = [
1590
- ReactTestComponent,
1591
- ReactElement,
1592
- DOMElement,
1593
- DOMCollection,
1594
- Immutable,
1595
- AsymmetricMatcher,
1596
- plugin
1597
- ];
1598
- const addSerializer = (plugin) => {
1599
- PLUGINS = [plugin].concat(PLUGINS);
1600
- };
1601
- const getSerializers = () => PLUGINS;
1602
-
1603
- const SNAPSHOT_VERSION = "1";
1604
- const writeSnapshotVersion = () => `// Vitest Snapshot v${SNAPSHOT_VERSION}`;
1605
- const testNameToKey = (testName, count) => `${testName} ${count}`;
1606
- const keyToTestName = (key) => {
1607
- if (!/ \d+$/.test(key))
1608
- throw new Error("Snapshot keys must end with a number.");
1609
- return key.replace(/ \d+$/, "");
1610
- };
1611
- const getSnapshotData = (snapshotPath, update) => {
1612
- const data = /* @__PURE__ */ Object.create(null);
1613
- let snapshotContents = "";
1614
- let dirty = false;
1615
- if (fs.existsSync(snapshotPath)) {
1616
- try {
1617
- snapshotContents = fs.readFileSync(snapshotPath, "utf8");
1618
- const populate = new Function("exports", snapshotContents);
1619
- populate(data);
1620
- } catch {
1621
- }
1622
- }
1623
- const isInvalid = snapshotContents;
1624
- if ((update === "all" || update === "new") && isInvalid)
1625
- dirty = true;
1626
- return { data, dirty };
1627
- };
1628
- const addExtraLineBreaks = (string) => string.includes("\n") ? `
1629
- ${string}
1630
- ` : string;
1631
- const removeExtraLineBreaks = (string) => string.length > 2 && string.startsWith("\n") && string.endsWith("\n") ? string.slice(1, -1) : string;
1632
- const escapeRegex = true;
1633
- const printFunctionName = false;
1634
- function serialize(val, indent = 2, formatOverrides = {}) {
1635
- return normalizeNewlines(
1636
- format_1(val, {
1637
- escapeRegex,
1638
- indent,
1639
- plugins: getSerializers(),
1640
- printFunctionName,
1641
- ...formatOverrides
1642
- })
1643
- );
1644
- }
1645
- function escapeBacktickString(str) {
1646
- return str.replace(/`|\\|\${/g, "\\$&");
1647
- }
1648
- function printBacktickString(str) {
1649
- return `\`${escapeBacktickString(str)}\``;
1650
- }
1651
- function ensureDirectoryExists(filePath) {
1652
- try {
1653
- fs.mkdirSync(join(dirname(filePath)), { recursive: true });
1654
- } catch {
1655
- }
1656
- }
1657
- function normalizeNewlines(string) {
1658
- return string.replace(/\r\n|\r/g, "\n");
1659
- }
1660
- async function saveSnapshotFile(snapshotData, snapshotPath) {
1661
- var _a, _b;
1662
- const snapshots = Object.keys(snapshotData).sort(naturalCompare$1.exports).map(
1663
- (key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`
1664
- );
1665
- const content = `${writeSnapshotVersion()}
1666
-
1667
- ${snapshots.join("\n\n")}
1668
- `;
1669
- const skipWriting = fs.existsSync(snapshotPath) && await ((_a = fs) == null ? void 0 : _a.promises.readFile(snapshotPath, "utf8")) === content;
1670
- if (skipWriting)
1671
- return;
1672
- ensureDirectoryExists(snapshotPath);
1673
- await ((_b = fs) == null ? void 0 : _b.promises.writeFile(
1674
- snapshotPath,
1675
- content,
1676
- "utf-8"
1677
- ));
1678
- }
1679
- function prepareExpected(expected) {
1680
- function findStartIndent() {
1681
- var _a, _b;
1682
- const matchObject = /^( +)}\s+$/m.exec(expected || "");
1683
- const objectIndent = (_a = matchObject == null ? void 0 : matchObject[1]) == null ? void 0 : _a.length;
1684
- if (objectIndent)
1685
- return objectIndent;
1686
- const matchText = /^\n( +)"/.exec(expected || "");
1687
- return ((_b = matchText == null ? void 0 : matchText[1]) == null ? void 0 : _b.length) || 0;
1688
- }
1689
- const startIndent = findStartIndent();
1690
- let expectedTrimmed = expected == null ? void 0 : expected.trim();
1691
- if (startIndent) {
1692
- expectedTrimmed = expectedTrimmed == null ? void 0 : expectedTrimmed.replace(new RegExp(`^${" ".repeat(startIndent)}`, "gm"), "").replace(/ +}$/, "}");
1693
- }
1694
- return expectedTrimmed;
1695
- }
1696
- function deepMergeArray(target = [], source = []) {
1697
- const mergedOutput = Array.from(target);
1698
- source.forEach((sourceElement, index) => {
1699
- const targetElement = mergedOutput[index];
1700
- if (Array.isArray(target[index])) {
1701
- mergedOutput[index] = deepMergeArray(target[index], sourceElement);
1702
- } else if (isObject$1(targetElement)) {
1703
- mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement);
1704
- } else {
1705
- mergedOutput[index] = sourceElement;
1706
- }
1707
- });
1708
- return mergedOutput;
1709
- }
1710
- function deepMergeSnapshot(target, source) {
1711
- if (isObject$1(target) && isObject$1(source)) {
1712
- const mergedOutput = { ...target };
1713
- Object.keys(source).forEach((key) => {
1714
- if (isObject$1(source[key]) && !source[key].$$typeof) {
1715
- if (!(key in target))
1716
- Object.assign(mergedOutput, { [key]: source[key] });
1717
- else
1718
- mergedOutput[key] = deepMergeSnapshot(target[key], source[key]);
1719
- } else if (Array.isArray(source[key])) {
1720
- mergedOutput[key] = deepMergeArray(target[key], source[key]);
1721
- } else {
1722
- Object.assign(mergedOutput, { [key]: source[key] });
1723
- }
1724
- });
1725
- return mergedOutput;
1726
- } else if (Array.isArray(target) && Array.isArray(source)) {
1727
- return deepMergeArray(target, source);
1728
- }
1729
- return target;
1730
- }
1731
-
1732
- async function saveInlineSnapshots(snapshots) {
1733
- const MagicString = (await import('./chunk-magic-string.3a794426.js')).default;
1734
- const files = new Set(snapshots.map((i) => i.file));
1735
- await Promise.all(Array.from(files).map(async (file) => {
1736
- const snaps = snapshots.filter((i) => i.file === file);
1737
- const code = await promises.readFile(file, "utf8");
1738
- const s = new MagicString(code);
1739
- for (const snap of snaps) {
1740
- const index = positionToOffset(code, snap.line, snap.column);
1741
- replaceInlineSnap(code, s, index, snap.snapshot);
1742
- }
1743
- const transformed = s.toString();
1744
- if (transformed !== code)
1745
- await promises.writeFile(file, transformed, "utf-8");
1746
- }));
1747
- }
1748
- const startObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\S\s]*\*\/\s*|\/\/.*\s+)*\s*({)/m;
1749
- function replaceObjectSnap(code, s, index, newSnap) {
1750
- code = code.slice(index);
1751
- const startMatch = startObjectRegex.exec(code);
1752
- if (!startMatch)
1753
- return false;
1754
- code = code.slice(startMatch.index);
1755
- const charIndex = getCallLastIndex(code);
1756
- if (charIndex === null)
1757
- return false;
1758
- s.appendLeft(index + startMatch.index + charIndex, `, ${prepareSnapString(newSnap, code, index)}`);
1759
- return true;
1760
- }
1761
- function prepareSnapString(snap, source, index) {
1762
- const lineNumber = offsetToLineNumber(source, index);
1763
- const line = source.split(lineSplitRE)[lineNumber - 1];
1764
- const indent = line.match(/^\s*/)[0] || "";
1765
- const indentNext = indent.includes(" ") ? `${indent} ` : `${indent} `;
1766
- const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g);
1767
- const isOneline = lines.length <= 1;
1768
- const quote = isOneline ? "'" : "`";
1769
- if (isOneline)
1770
- return `'${lines.join("\n").replace(/'/g, "\\'")}'`;
1771
- else
1772
- return `${quote}
1773
- ${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\${/g, "\\${")}
1774
- ${indent}${quote}`;
1775
- }
1776
- const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\S\s]*\*\/\s*|\/\/.*\s+)*\s*[\w_$]*(['"`\)])/m;
1777
- function replaceInlineSnap(code, s, index, newSnap) {
1778
- const startMatch = startRegex.exec(code.slice(index));
1779
- if (!startMatch)
1780
- return replaceObjectSnap(code, s, index, newSnap);
1781
- const quote = startMatch[1];
1782
- const startIndex = index + startMatch.index + startMatch[0].length;
1783
- const snapString = prepareSnapString(newSnap, code, index);
1784
- if (quote === ")") {
1785
- s.appendRight(startIndex - 1, snapString);
1786
- return true;
1787
- }
1788
- const quoteEndRE = new RegExp(`(?:^|[^\\\\])${quote}`);
1789
- const endMatch = quoteEndRE.exec(code.slice(startIndex));
1790
- if (!endMatch)
1791
- return false;
1792
- const endIndex = startIndex + endMatch.index + endMatch[0].length;
1793
- s.overwrite(startIndex - 1, endIndex, snapString);
1794
- return true;
1795
- }
1796
- const INDENTATION_REGEX = /^([^\S\n]*)\S/m;
1797
- function stripSnapshotIndentation(inlineSnapshot) {
1798
- const match = inlineSnapshot.match(INDENTATION_REGEX);
1799
- if (!match || !match[1]) {
1800
- return inlineSnapshot;
1801
- }
1802
- const indentation = match[1];
1803
- const lines = inlineSnapshot.split(/\n/g);
1804
- if (lines.length <= 2) {
1805
- return inlineSnapshot;
1806
- }
1807
- if (lines[0].trim() !== "" || lines[lines.length - 1].trim() !== "") {
1808
- return inlineSnapshot;
1809
- }
1810
- for (let i = 1; i < lines.length - 1; i++) {
1811
- if (lines[i] !== "") {
1812
- if (lines[i].indexOf(indentation) !== 0) {
1813
- return inlineSnapshot;
1814
- }
1815
- lines[i] = lines[i].substring(indentation.length);
1816
- }
1817
- }
1818
- lines[lines.length - 1] = "";
1819
- inlineSnapshot = lines.join("\n");
1820
- return inlineSnapshot;
1821
- }
1822
-
1823
- class SnapshotState {
1824
- constructor(testFilePath, snapshotPath, options) {
1825
- this.testFilePath = testFilePath;
1826
- this.snapshotPath = snapshotPath;
1827
- const { data, dirty } = getSnapshotData(
1828
- this.snapshotPath,
1829
- options.updateSnapshot
1830
- );
1831
- this._initialData = data;
1832
- this._snapshotData = data;
1833
- this._dirty = dirty;
1834
- this._inlineSnapshots = [];
1835
- this._uncheckedKeys = new Set(Object.keys(this._snapshotData));
1836
- this._counters = /* @__PURE__ */ new Map();
1837
- this.expand = options.expand || false;
1838
- this.added = 0;
1839
- this.matched = 0;
1840
- this.unmatched = 0;
1841
- this._updateSnapshot = options.updateSnapshot;
1842
- this.updated = 0;
1843
- this._snapshotFormat = {
1844
- printBasicPrototype: false,
1845
- ...options.snapshotFormat
1846
- };
1847
- }
1848
- markSnapshotsAsCheckedForTest(testName) {
1849
- this._uncheckedKeys.forEach((uncheckedKey) => {
1850
- if (keyToTestName(uncheckedKey) === testName)
1851
- this._uncheckedKeys.delete(uncheckedKey);
1852
- });
1853
- }
1854
- _inferInlineSnapshotStack(stacks) {
1855
- const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/));
1856
- if (promiseIndex !== -1)
1857
- return stacks[promiseIndex + 3];
1858
- const stackIndex = stacks.findIndex((i) => i.method.includes("__VITEST_INLINE_SNAPSHOT__"));
1859
- return stackIndex !== -1 ? stacks[stackIndex + 2] : null;
1860
- }
1861
- _addSnapshot(key, receivedSerialized, options) {
1862
- this._dirty = true;
1863
- if (options.isInline) {
1864
- const error = options.error || new Error("Unknown error");
1865
- const stacks = parseStacktrace(error, true);
1866
- stacks.forEach((i) => i.file = slash(i.file));
1867
- const stack = this._inferInlineSnapshotStack(stacks);
1868
- if (!stack) {
1869
- throw new Error(
1870
- `Vitest: Couldn't infer stack frame for inline snapshot.
1871
- ${JSON.stringify(stacks)}`
1872
- );
1873
- }
1874
- stack.column--;
1875
- this._inlineSnapshots.push({
1876
- snapshot: receivedSerialized,
1877
- ...stack
1878
- });
1879
- } else {
1880
- this._snapshotData[key] = receivedSerialized;
1881
- }
1882
- }
1883
- clear() {
1884
- this._snapshotData = this._initialData;
1885
- this._counters = /* @__PURE__ */ new Map();
1886
- this.added = 0;
1887
- this.matched = 0;
1888
- this.unmatched = 0;
1889
- this.updated = 0;
1890
- this._dirty = false;
1891
- }
1892
- async save() {
1893
- const hasExternalSnapshots = Object.keys(this._snapshotData).length;
1894
- const hasInlineSnapshots = this._inlineSnapshots.length;
1895
- const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots;
1896
- const status = {
1897
- deleted: false,
1898
- saved: false
1899
- };
1900
- if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) {
1901
- if (hasExternalSnapshots)
1902
- await saveSnapshotFile(this._snapshotData, this.snapshotPath);
1903
- if (hasInlineSnapshots)
1904
- await saveInlineSnapshots(this._inlineSnapshots);
1905
- status.saved = true;
1906
- } else if (!hasExternalSnapshots && fs.existsSync(this.snapshotPath)) {
1907
- if (this._updateSnapshot === "all")
1908
- fs.unlinkSync(this.snapshotPath);
1909
- status.deleted = true;
1910
- }
1911
- return status;
1912
- }
1913
- getUncheckedCount() {
1914
- return this._uncheckedKeys.size || 0;
1915
- }
1916
- getUncheckedKeys() {
1917
- return Array.from(this._uncheckedKeys);
1918
- }
1919
- removeUncheckedKeys() {
1920
- if (this._updateSnapshot === "all" && this._uncheckedKeys.size) {
1921
- this._dirty = true;
1922
- this._uncheckedKeys.forEach((key) => delete this._snapshotData[key]);
1923
- this._uncheckedKeys.clear();
1924
- }
1925
- }
1926
- match({
1927
- testName,
1928
- received,
1929
- key,
1930
- inlineSnapshot,
1931
- isInline,
1932
- error
1933
- }) {
1934
- this._counters.set(testName, (this._counters.get(testName) || 0) + 1);
1935
- const count = Number(this._counters.get(testName));
1936
- if (!key)
1937
- key = testNameToKey(testName, count);
1938
- if (!(isInline && this._snapshotData[key] !== void 0))
1939
- this._uncheckedKeys.delete(key);
1940
- const receivedSerialized = addExtraLineBreaks(serialize(received, void 0, this._snapshotFormat));
1941
- const expected = isInline ? inlineSnapshot : this._snapshotData[key];
1942
- const expectedTrimmed = prepareExpected(expected);
1943
- const pass = expectedTrimmed === prepareExpected(receivedSerialized);
1944
- const hasSnapshot = expected !== void 0;
1945
- const snapshotIsPersisted = isInline || fs.existsSync(this.snapshotPath);
1946
- if (pass && !isInline) {
1947
- this._snapshotData[key] = receivedSerialized;
1948
- }
1949
- if (hasSnapshot && this._updateSnapshot === "all" || (!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all")) {
1950
- if (this._updateSnapshot === "all") {
1951
- if (!pass) {
1952
- if (hasSnapshot)
1953
- this.updated++;
1954
- else
1955
- this.added++;
1956
- this._addSnapshot(key, receivedSerialized, { error, isInline });
1957
- } else {
1958
- this.matched++;
1959
- }
1960
- } else {
1961
- this._addSnapshot(key, receivedSerialized, { error, isInline });
1962
- this.added++;
1963
- }
1964
- return {
1965
- actual: "",
1966
- count,
1967
- expected: "",
1968
- key,
1969
- pass: true
1970
- };
1971
- } else {
1972
- if (!pass) {
1973
- this.unmatched++;
1974
- return {
1975
- actual: removeExtraLineBreaks(receivedSerialized),
1976
- count,
1977
- expected: expectedTrimmed !== void 0 ? removeExtraLineBreaks(expectedTrimmed) : void 0,
1978
- key,
1979
- pass: false
1980
- };
1981
- } else {
1982
- this.matched++;
1983
- return {
1984
- actual: "",
1985
- count,
1986
- expected: "",
1987
- key,
1988
- pass: true
1989
- };
1990
- }
1991
- }
1992
- }
1993
- async pack() {
1994
- const snapshot = {
1995
- filepath: this.testFilePath,
1996
- added: 0,
1997
- fileDeleted: false,
1998
- matched: 0,
1999
- unchecked: 0,
2000
- uncheckedKeys: [],
2001
- unmatched: 0,
2002
- updated: 0
2003
- };
2004
- const uncheckedCount = this.getUncheckedCount();
2005
- const uncheckedKeys = this.getUncheckedKeys();
2006
- if (uncheckedCount)
2007
- this.removeUncheckedKeys();
2008
- const status = await this.save();
2009
- snapshot.fileDeleted = status.deleted;
2010
- snapshot.added = this.added;
2011
- snapshot.matched = this.matched;
2012
- snapshot.unmatched = this.unmatched;
2013
- snapshot.updated = this.updated;
2014
- snapshot.unchecked = !status.deleted ? uncheckedCount : 0;
2015
- snapshot.uncheckedKeys = Array.from(uncheckedKeys);
2016
- return snapshot;
2017
- }
2018
- }
2019
-
2020
- class SnapshotClient {
2021
- constructor() {
2022
- this.snapshotStateMap = /* @__PURE__ */ new Map();
2023
- }
2024
- async setTest(test) {
2025
- var _a;
2026
- this.test = test;
2027
- if (((_a = this.snapshotState) == null ? void 0 : _a.testFilePath) !== this.test.file.filepath) {
2028
- this.saveCurrent();
2029
- const filePath = this.test.file.filepath;
2030
- if (!this.getSnapshotState(test)) {
2031
- this.snapshotStateMap.set(
2032
- filePath,
2033
- new SnapshotState(
2034
- filePath,
2035
- await rpc().resolveSnapshotPath(filePath),
2036
- getWorkerState().config.snapshotOptions
2037
- )
2038
- );
2039
- }
2040
- this.snapshotState = this.getSnapshotState(test);
2041
- }
2042
- }
2043
- getSnapshotState(test) {
2044
- return this.snapshotStateMap.get(test.file.filepath);
2045
- }
2046
- clearTest() {
2047
- this.test = void 0;
2048
- }
2049
- skipTestSnapshots(test) {
2050
- var _a;
2051
- (_a = this.snapshotState) == null ? void 0 : _a.markSnapshotsAsCheckedForTest(test.name);
2052
- }
2053
- assert(options) {
2054
- const {
2055
- test = this.test,
2056
- message,
2057
- isInline = false,
2058
- properties,
2059
- inlineSnapshot,
2060
- error,
2061
- errorMessage
2062
- } = options;
2063
- let { received } = options;
2064
- if (!test)
2065
- throw new Error("Snapshot cannot be used outside of test");
2066
- if (typeof properties === "object") {
2067
- if (typeof received !== "object" || !received)
2068
- throw new Error("Received value must be an object when the matcher has properties");
2069
- try {
2070
- const pass2 = equals(received, properties, [iterableEquality, subsetEquality]);
2071
- if (!pass2)
2072
- expect(received).equals(properties);
2073
- else
2074
- received = deepMergeSnapshot(received, properties);
2075
- } catch (err) {
2076
- err.message = errorMessage || "Snapshot mismatched";
2077
- throw err;
2078
- }
2079
- }
2080
- const testName = [
2081
- ...getNames(test).slice(1),
2082
- ...message ? [message] : []
2083
- ].join(" > ");
2084
- const snapshotState = this.getSnapshotState(test);
2085
- const { actual, expected, key, pass } = snapshotState.match({
2086
- testName,
2087
- received,
2088
- isInline,
2089
- error,
2090
- inlineSnapshot
2091
- });
2092
- if (!pass) {
2093
- try {
2094
- expect(actual.trim()).equals(expected ? expected.trim() : "");
2095
- } catch (error2) {
2096
- error2.message = errorMessage || `Snapshot \`${key || "unknown"}\` mismatched`;
2097
- throw error2;
2098
- }
2099
- }
2100
- }
2101
- async saveCurrent() {
2102
- if (!this.snapshotState)
2103
- return;
2104
- const result = await this.snapshotState.pack();
2105
- await rpc().snapshotSaved(result);
2106
- this.snapshotState = void 0;
2107
- }
2108
- clear() {
2109
- this.snapshotStateMap.clear();
2110
- }
2111
- }
2112
-
2113
- let _client;
2114
- function getSnapshotClient() {
2115
- if (!_client)
2116
- _client = new SnapshotClient();
2117
- return _client;
2118
- }
2119
- const getErrorMessage = (err) => {
2120
- if (err instanceof Error)
2121
- return err.message;
2122
- return err;
2123
- };
2124
- const getErrorString = (expected, promise) => {
2125
- if (typeof expected !== "function") {
2126
- if (!promise)
2127
- throw new Error(`expected must be a function, received ${typeof expected}`);
2128
- return getErrorMessage(expected);
2129
- }
2130
- try {
2131
- expected();
2132
- } catch (e) {
2133
- return getErrorMessage(e);
2134
- }
2135
- throw new Error("snapshot function didn't throw");
2136
- };
2137
- const SnapshotPlugin = (chai, utils) => {
2138
- for (const key of ["matchSnapshot", "toMatchSnapshot"]) {
2139
- utils.addMethod(
2140
- chai.Assertion.prototype,
2141
- key,
2142
- function(properties, message) {
2143
- const expected = utils.flag(this, "object");
2144
- const test = utils.flag(this, "vitest-test");
2145
- if (typeof properties === "string" && typeof message === "undefined") {
2146
- message = properties;
2147
- properties = void 0;
2148
- }
2149
- const errorMessage = utils.flag(this, "message");
2150
- getSnapshotClient().assert({
2151
- received: expected,
2152
- test,
2153
- message,
2154
- isInline: false,
2155
- properties,
2156
- errorMessage
2157
- });
2158
- }
2159
- );
2160
- }
2161
- utils.addMethod(
2162
- chai.Assertion.prototype,
2163
- "toMatchInlineSnapshot",
2164
- function __VITEST_INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
2165
- const expected = utils.flag(this, "object");
2166
- const error = utils.flag(this, "error");
2167
- const test = utils.flag(this, "vitest-test");
2168
- if (typeof properties === "string") {
2169
- message = inlineSnapshot;
2170
- inlineSnapshot = properties;
2171
- properties = void 0;
2172
- }
2173
- if (inlineSnapshot)
2174
- inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
2175
- const errorMessage = utils.flag(this, "message");
2176
- getSnapshotClient().assert({
2177
- received: expected,
2178
- test,
2179
- message,
2180
- isInline: true,
2181
- properties,
2182
- inlineSnapshot,
2183
- error,
2184
- errorMessage
2185
- });
2186
- }
2187
- );
2188
- utils.addMethod(
2189
- chai.Assertion.prototype,
2190
- "toThrowErrorMatchingSnapshot",
2191
- function(message) {
2192
- const expected = utils.flag(this, "object");
2193
- const test = utils.flag(this, "vitest-test");
2194
- const promise = utils.flag(this, "promise");
2195
- const errorMessage = utils.flag(this, "message");
2196
- getSnapshotClient().assert({
2197
- received: getErrorString(expected, promise),
2198
- test,
2199
- message,
2200
- errorMessage
2201
- });
2202
- }
2203
- );
2204
- utils.addMethod(
2205
- chai.Assertion.prototype,
2206
- "toThrowErrorMatchingInlineSnapshot",
2207
- function __VITEST_INLINE_SNAPSHOT__(inlineSnapshot, message) {
2208
- const expected = utils.flag(this, "object");
2209
- const error = utils.flag(this, "error");
2210
- const test = utils.flag(this, "vitest-test");
2211
- const promise = utils.flag(this, "promise");
2212
- const errorMessage = utils.flag(this, "message");
2213
- getSnapshotClient().assert({
2214
- received: getErrorString(expected, promise),
2215
- test,
2216
- message,
2217
- inlineSnapshot,
2218
- isInline: true,
2219
- error,
2220
- errorMessage
2221
- });
2222
- }
2223
- );
2224
- utils.addMethod(
2225
- chai.expect,
2226
- "addSnapshotSerializer",
2227
- addSerializer
2228
- );
2229
- };
2230
-
2231
- var chai$1 = /*#__PURE__*/Object.freeze({
2232
- __proto__: null,
2233
- getSnapshotClient: getSnapshotClient,
2234
- SnapshotPlugin: SnapshotPlugin
2235
- });
2236
-
2237
- chai$2.use(JestExtend);
2238
- chai$2.use(JestChaiExpect);
2239
- chai$2.use(Subset);
2240
- chai$2.use(SnapshotPlugin);
2241
- chai$2.use(JestAsymmetricMatchers);
2242
-
2243
- function createExpect(test) {
2244
- var _a;
2245
- const expect = (value, message) => {
2246
- const { assertionCalls } = getState(expect);
2247
- setState({ assertionCalls: assertionCalls + 1 }, expect);
2248
- const assert2 = chai$2.expect(value, message);
2249
- if (test)
2250
- return assert2.withTest(test);
2251
- else
2252
- return assert2;
2253
- };
2254
- Object.assign(expect, chai$2.expect);
2255
- expect.getState = () => getState(expect);
2256
- expect.setState = (state) => setState(state, expect);
2257
- const globalState = getState(globalThis[GLOBAL_EXPECT]) || {};
2258
- setState({
2259
- ...globalState,
2260
- assertionCalls: 0,
2261
- isExpectingAssertions: false,
2262
- isExpectingAssertionsError: null,
2263
- expectedAssertionsNumber: null,
2264
- expectedAssertionsNumberErrorGen: null,
2265
- environment: getCurrentEnvironment(),
2266
- testPath: test ? (_a = test.suite.file) == null ? void 0 : _a.filepath : globalState.testPath,
2267
- currentTestName: test ? getFullName(test) : globalState.currentTestName
2268
- }, expect);
2269
- expect.extend = (matchers) => chai$2.expect.extend(expect, matchers);
2270
- function assertions(expected) {
2271
- const errorGen = () => new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
2272
- if (Error.captureStackTrace)
2273
- Error.captureStackTrace(errorGen(), assertions);
2274
- expect.setState({
2275
- expectedAssertionsNumber: expected,
2276
- expectedAssertionsNumberErrorGen: errorGen
2277
- });
2278
- }
2279
- function hasAssertions() {
2280
- const error = new Error("expected any number of assertion, but got none");
2281
- if (Error.captureStackTrace)
2282
- Error.captureStackTrace(error, hasAssertions);
2283
- expect.setState({
2284
- isExpectingAssertions: true,
2285
- isExpectingAssertionsError: error
2286
- });
2287
- }
2288
- chai$2.util.addMethod(expect, "assertions", assertions);
2289
- chai$2.util.addMethod(expect, "hasAssertions", hasAssertions);
2290
- return expect;
2291
- }
2292
- const globalExpect = createExpect();
2293
- Object.defineProperty(globalThis, GLOBAL_EXPECT, {
2294
- value: globalExpect,
2295
- writable: true,
2296
- configurable: true
2297
- });
2298
-
2299
- const collectorContext = {
2300
- tasks: [],
2301
- currentSuite: null
2302
- };
2303
- function collectTask(task) {
2304
- var _a;
2305
- (_a = collectorContext.currentSuite) == null ? void 0 : _a.tasks.push(task);
2306
- }
2307
- async function runWithSuite(suite, fn) {
2308
- const prev = collectorContext.currentSuite;
2309
- collectorContext.currentSuite = suite;
2310
- await fn();
2311
- collectorContext.currentSuite = prev;
2312
- }
2313
- function getDefaultTestTimeout() {
2314
- return getWorkerState().config.testTimeout;
2315
- }
2316
- function getDefaultHookTimeout() {
2317
- return getWorkerState().config.hookTimeout;
2318
- }
2319
- function withTimeout(fn, timeout = getDefaultTestTimeout(), isHook = false) {
2320
- if (timeout <= 0 || timeout === Infinity)
2321
- return fn;
2322
- return (...args) => {
2323
- return Promise.race([fn(...args), new Promise((resolve, reject) => {
2324
- var _a;
2325
- const timer = safeSetTimeout(() => {
2326
- safeClearTimeout(timer);
2327
- reject(new Error(makeTimeoutMsg(isHook, timeout)));
2328
- }, timeout);
2329
- (_a = timer.unref) == null ? void 0 : _a.call(timer);
2330
- })]);
2331
- };
2332
- }
2333
- function createTestContext(test) {
2334
- const context = function() {
2335
- throw new Error("done() callback is deprecated, use promise instead");
2336
- };
2337
- context.meta = test;
2338
- let _expect;
2339
- Object.defineProperty(context, "expect", {
2340
- get() {
2341
- if (!_expect)
2342
- _expect = createExpect(test);
2343
- return _expect;
2344
- }
2345
- });
2346
- Object.defineProperty(context, "_local", {
2347
- get() {
2348
- return _expect != null;
2349
- }
2350
- });
2351
- context.onTestFailed = (fn) => {
2352
- test.onFailed || (test.onFailed = []);
2353
- test.onFailed.push(fn);
2354
- };
2355
- return context;
2356
- }
2357
- function makeTimeoutMsg(isHook, timeout) {
2358
- return `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.
2359
- If this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`;
2360
- }
2361
-
2362
- const fnMap = /* @__PURE__ */ new WeakMap();
2363
- const hooksMap = /* @__PURE__ */ new WeakMap();
2364
- const benchOptsMap = /* @__PURE__ */ new WeakMap();
2365
- function setFn(key, fn) {
2366
- fnMap.set(key, fn);
2367
- }
2368
- function getFn(key) {
2369
- return fnMap.get(key);
2370
- }
2371
- function setHooks(key, hooks) {
2372
- hooksMap.set(key, hooks);
2373
- }
2374
- function getHooks(key) {
2375
- return hooksMap.get(key);
2376
- }
2377
- function setBenchOptions(key, val) {
2378
- benchOptsMap.set(key, val);
2379
- }
2380
- function getBenchOptions(key) {
2381
- return benchOptsMap.get(key);
2382
- }
2383
-
2384
- const suite = createSuite();
2385
- const test = createTest(
2386
- function(name, fn, options) {
2387
- getCurrentSuite().test.fn.call(this, name, fn, options);
2388
- }
2389
- );
2390
- const bench = createBenchmark(
2391
- function(name, fn = noop, options = {}) {
2392
- getCurrentSuite().benchmark.fn.call(this, name, fn, options);
2393
- }
2394
- );
2395
- const describe = suite;
2396
- const it = test;
2397
- const workerState = getWorkerState();
2398
- const defaultSuite = workerState.config.sequence.shuffle ? suite.shuffle("") : suite("");
2399
- function clearCollectorContext() {
2400
- collectorContext.tasks.length = 0;
2401
- defaultSuite.clear();
2402
- collectorContext.currentSuite = defaultSuite;
2403
- }
2404
- function getCurrentSuite() {
2405
- return collectorContext.currentSuite || defaultSuite;
2406
- }
2407
- function createSuiteHooks() {
2408
- return {
2409
- beforeAll: [],
2410
- afterAll: [],
2411
- beforeEach: [],
2412
- afterEach: []
2413
- };
2414
- }
2415
- function createSuiteCollector(name, factory = () => {
2416
- }, mode, concurrent, shuffle, suiteOptions) {
2417
- const tasks = [];
2418
- const factoryQueue = [];
2419
- let suite2;
2420
- initSuite();
2421
- const test2 = createTest(function(name2, fn = noop, options = suiteOptions) {
2422
- if (!isRunningInTest())
2423
- throw new Error("`test()` and `it()` is only available in test mode.");
2424
- const mode2 = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
2425
- if (typeof options === "number")
2426
- options = { timeout: options };
2427
- const test3 = {
2428
- id: "",
2429
- type: "test",
2430
- name: name2,
2431
- mode: mode2,
2432
- suite: void 0,
2433
- fails: this.fails,
2434
- retry: options == null ? void 0 : options.retry
2435
- };
2436
- if (this.concurrent || concurrent)
2437
- test3.concurrent = true;
2438
- if (shuffle)
2439
- test3.shuffle = true;
2440
- const context = createTestContext(test3);
2441
- Object.defineProperty(test3, "context", {
2442
- value: context,
2443
- enumerable: false
2444
- });
2445
- setFn(test3, withTimeout(
2446
- () => fn(context),
2447
- options == null ? void 0 : options.timeout
2448
- ));
2449
- tasks.push(test3);
2450
- });
2451
- const benchmark = createBenchmark(function(name2, fn = noop, options = {}) {
2452
- const mode2 = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
2453
- if (!isRunningInBenchmark())
2454
- throw new Error("`bench()` is only available in benchmark mode. Run with `vitest bench` instead.");
2455
- const benchmark2 = {
2456
- type: "benchmark",
2457
- id: "",
2458
- name: name2,
2459
- mode: mode2,
2460
- suite: void 0
2461
- };
2462
- setFn(benchmark2, fn);
2463
- setBenchOptions(benchmark2, options);
2464
- tasks.push(benchmark2);
2465
- });
2466
- const collector = {
2467
- type: "collector",
2468
- name,
2469
- mode,
2470
- test: test2,
2471
- tasks,
2472
- benchmark,
2473
- collect,
2474
- clear,
2475
- on: addHook
2476
- };
2477
- function addHook(name2, ...fn) {
2478
- getHooks(suite2)[name2].push(...fn);
2479
- }
2480
- function initSuite() {
2481
- suite2 = {
2482
- id: "",
2483
- type: "suite",
2484
- name,
2485
- mode,
2486
- shuffle,
2487
- tasks: []
2488
- };
2489
- setHooks(suite2, createSuiteHooks());
2490
- }
2491
- function clear() {
2492
- tasks.length = 0;
2493
- factoryQueue.length = 0;
2494
- initSuite();
2495
- }
2496
- async function collect(file) {
2497
- factoryQueue.length = 0;
2498
- if (factory)
2499
- await runWithSuite(collector, () => factory(test2));
2500
- const allChildren = [];
2501
- for (const i of [...factoryQueue, ...tasks])
2502
- allChildren.push(i.type === "collector" ? await i.collect(file) : i);
2503
- suite2.file = file;
2504
- suite2.tasks = allChildren;
2505
- allChildren.forEach((task) => {
2506
- task.suite = suite2;
2507
- if (file)
2508
- task.file = file;
2509
- });
2510
- return suite2;
2511
- }
2512
- collectTask(collector);
2513
- return collector;
2514
- }
2515
- function createSuite() {
2516
- function suiteFn(name, factory, options) {
2517
- const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
2518
- return createSuiteCollector(name, factory, mode, this.concurrent, this.shuffle, options);
2519
- }
2520
- suiteFn.each = function(cases, ...args) {
2521
- const suite2 = this.withContext();
2522
- if (Array.isArray(cases) && args.length)
2523
- cases = formatTemplateString(cases, args);
2524
- return (name, fn, options) => {
2525
- const arrayOnlyCases = cases.every(Array.isArray);
2526
- cases.forEach((i, idx) => {
2527
- const items = Array.isArray(i) ? i : [i];
2528
- arrayOnlyCases ? suite2(formatTitle(name, items, idx), () => fn(...items), options) : suite2(formatTitle(name, items, idx), () => fn(i), options);
2529
- });
2530
- };
2531
- };
2532
- suiteFn.skipIf = (condition) => condition ? suite.skip : suite;
2533
- suiteFn.runIf = (condition) => condition ? suite : suite.skip;
2534
- return createChainable(
2535
- ["concurrent", "shuffle", "skip", "only", "todo"],
2536
- suiteFn
2537
- );
2538
- }
2539
- function createTest(fn) {
2540
- const testFn = fn;
2541
- testFn.each = function(cases, ...args) {
2542
- const test2 = this.withContext();
2543
- if (Array.isArray(cases) && args.length)
2544
- cases = formatTemplateString(cases, args);
2545
- return (name, fn2, options) => {
2546
- const arrayOnlyCases = cases.every(Array.isArray);
2547
- cases.forEach((i, idx) => {
2548
- const items = Array.isArray(i) ? i : [i];
2549
- arrayOnlyCases ? test2(formatTitle(name, items, idx), () => fn2(...items), options) : test2(formatTitle(name, items, idx), () => fn2(i), options);
2550
- });
2551
- };
2552
- };
2553
- testFn.skipIf = (condition) => condition ? test.skip : test;
2554
- testFn.runIf = (condition) => condition ? test : test.skip;
2555
- return createChainable(
2556
- ["concurrent", "skip", "only", "todo", "fails"],
2557
- testFn
2558
- );
2559
- }
2560
- function createBenchmark(fn) {
2561
- const benchmark = createChainable(
2562
- ["skip", "only", "todo"],
2563
- fn
2564
- );
2565
- benchmark.skipIf = (condition) => condition ? benchmark.skip : benchmark;
2566
- benchmark.runIf = (condition) => condition ? benchmark : benchmark.skip;
2567
- return benchmark;
2568
- }
2569
- function formatTitle(template, items, idx) {
2570
- if (template.includes("%#")) {
2571
- template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/__vitest_escaped_%__/g, "%%");
2572
- }
2573
- const count = template.split("%").length - 1;
2574
- let formatted = util$1.format(template, ...items.slice(0, count));
2575
- if (isObject$1(items[0])) {
2576
- formatted = formatted.replace(
2577
- /\$([$\w_.]+)/g,
2578
- (_, key) => util.objDisplay(objectAttr(items[0], key))
2579
- );
2580
- }
2581
- return formatted;
2582
- }
2583
- function formatTemplateString(cases, args) {
2584
- const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0];
2585
- const res = [];
2586
- for (let i = 0; i < Math.floor(args.length / header.length); i++) {
2587
- const oneCase = {};
2588
- for (let j = 0; j < header.length; j++)
2589
- oneCase[header[j]] = args[i * header.length + j];
2590
- res.push(oneCase);
2591
- }
2592
- return res;
2593
- }
2594
-
2595
- export { GLOBAL_EXPECT as G, getDefaultHookTimeout as a, bench as b, createExpect as c, describe as d, globalExpect as e, clearCollectorContext as f, getCurrentSuite as g, defaultSuite as h, it as i, setHooks as j, getHooks as k, collectorContext as l, getBenchOptions as m, getFn as n, setState as o, getSnapshotClient as p, getState as q, createSuiteHooks as r, suite as s, test as t, chai$1 as u, withTimeout as w };