vitest 0.0.100 → 0.0.104

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ import { n as nanoid } from './index-9e71c815.js';
2
+ import { n as noop } from './utils-49e5008c.js';
3
+
4
+ var __defProp = Object.defineProperty;
5
+ var __defProps = Object.defineProperties;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ function createChainable(keys, fn) {
24
+ function create(obj) {
25
+ const chain2 = function(...args) {
26
+ return fn.apply(obj, args);
27
+ };
28
+ for (const key of keys) {
29
+ Object.defineProperty(chain2, key, {
30
+ get() {
31
+ return create(__spreadProps(__spreadValues({}, obj), { [key]: true }));
32
+ }
33
+ });
34
+ }
35
+ return chain2;
36
+ }
37
+ const chain = create({});
38
+ chain.fn = fn;
39
+ return chain;
40
+ }
41
+
42
+ const context = {
43
+ tasks: [],
44
+ currentSuite: null
45
+ };
46
+ function collectTask(task) {
47
+ var _a;
48
+ (_a = context.currentSuite) == null ? void 0 : _a.tasks.push(task);
49
+ }
50
+ async function runWithSuite(suite, fn) {
51
+ const prev = context.currentSuite;
52
+ context.currentSuite = suite;
53
+ await fn();
54
+ context.currentSuite = prev;
55
+ }
56
+ function getDefaultTestTimeout() {
57
+ return process.__vitest_worker__.config.testTimeout;
58
+ }
59
+ function getDefaultHookTimeout() {
60
+ return process.__vitest_worker__.config.hookTimeout;
61
+ }
62
+ function withTimeout(fn, _timeout) {
63
+ const timeout = _timeout ?? getDefaultTestTimeout();
64
+ if (timeout <= 0 || timeout === Infinity)
65
+ return fn;
66
+ return (...args) => {
67
+ return Promise.race([fn(...args), new Promise((resolve, reject) => {
68
+ const timer = setTimeout(() => {
69
+ clearTimeout(timer);
70
+ reject(new Error(`Test timed out in ${timeout}ms.`));
71
+ }, timeout);
72
+ timer.unref();
73
+ })]);
74
+ };
75
+ }
76
+ function ensureAsyncTest(fn) {
77
+ if (!fn.length)
78
+ return fn;
79
+ return () => new Promise((resolve, reject) => {
80
+ const done = (...args) => args[0] ? reject(args[0]) : resolve();
81
+ fn(done);
82
+ });
83
+ }
84
+ function normalizeTest(fn, timeout) {
85
+ return withTimeout(ensureAsyncTest(fn), timeout);
86
+ }
87
+
88
+ const fnMap = /* @__PURE__ */ new WeakMap();
89
+ const hooksMap = /* @__PURE__ */ new WeakMap();
90
+ function setFn(key, fn) {
91
+ fnMap.set(key, fn);
92
+ }
93
+ function getFn(key) {
94
+ return fnMap.get(key);
95
+ }
96
+ function setHooks(key, hooks) {
97
+ hooksMap.set(key, hooks);
98
+ }
99
+ function getHooks(key) {
100
+ return hooksMap.get(key);
101
+ }
102
+
103
+ const suite = createSuite();
104
+ const test = createChainable(["concurrent", "skip", "only", "todo", "fails"], function(name, fn, timeout) {
105
+ getCurrentSuite().test.fn.call(this, name, fn, timeout);
106
+ });
107
+ const describe = suite;
108
+ const it = test;
109
+ const defaultSuite = suite("");
110
+ function clearContext() {
111
+ context.tasks.length = 0;
112
+ defaultSuite.clear();
113
+ context.currentSuite = defaultSuite;
114
+ }
115
+ function getCurrentSuite() {
116
+ return context.currentSuite || defaultSuite;
117
+ }
118
+ function createSuiteHooks() {
119
+ return {
120
+ beforeAll: [],
121
+ afterAll: [],
122
+ beforeEach: [],
123
+ afterEach: []
124
+ };
125
+ }
126
+ function createSuiteCollector(name, factory = () => {
127
+ }, mode, suiteComputeMode) {
128
+ const tasks = [];
129
+ const factoryQueue = [];
130
+ let suite2;
131
+ initSuite();
132
+ const test2 = createChainable(["concurrent", "skip", "only", "todo", "fails"], function(name2, fn, timeout) {
133
+ const mode2 = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
134
+ const computeMode = this.concurrent ? "concurrent" : void 0;
135
+ const test3 = {
136
+ id: nanoid(),
137
+ type: "test",
138
+ name: name2,
139
+ mode: mode2,
140
+ computeMode: computeMode ?? (suiteComputeMode ?? "serial"),
141
+ suite: void 0,
142
+ fails: this.fails
143
+ };
144
+ setFn(test3, normalizeTest(fn || noop, timeout));
145
+ tasks.push(test3);
146
+ });
147
+ const collector = {
148
+ type: "collector",
149
+ name,
150
+ mode,
151
+ test: test2,
152
+ tasks,
153
+ collect,
154
+ clear,
155
+ on: addHook
156
+ };
157
+ function addHook(name2, ...fn) {
158
+ getHooks(suite2)[name2].push(...fn);
159
+ }
160
+ function initSuite() {
161
+ suite2 = {
162
+ id: nanoid(),
163
+ type: "suite",
164
+ computeMode: "serial",
165
+ name,
166
+ mode,
167
+ tasks: []
168
+ };
169
+ setHooks(suite2, createSuiteHooks());
170
+ }
171
+ function clear() {
172
+ tasks.length = 0;
173
+ factoryQueue.length = 0;
174
+ initSuite();
175
+ }
176
+ async function collect(file) {
177
+ factoryQueue.length = 0;
178
+ if (factory)
179
+ await runWithSuite(collector, () => factory(test2));
180
+ const allChildren = await Promise.all([...factoryQueue, ...tasks].map((i) => i.type === "collector" ? i.collect(file) : i));
181
+ suite2.file = file;
182
+ suite2.tasks = allChildren;
183
+ allChildren.forEach((task) => {
184
+ task.suite = suite2;
185
+ if (file)
186
+ task.file = file;
187
+ });
188
+ return suite2;
189
+ }
190
+ collectTask(collector);
191
+ return collector;
192
+ }
193
+ function createSuite() {
194
+ return createChainable(["concurrent", "skip", "only", "todo"], function(name, factory) {
195
+ const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
196
+ const computeMode = this.concurrent ? "concurrent" : void 0;
197
+ return createSuiteCollector(name, factory, mode, computeMode);
198
+ });
199
+ }
200
+
201
+ export { getDefaultHookTimeout as a, defaultSuite as b, clearContext as c, describe as d, setHooks as e, getHooks as f, getCurrentSuite as g, context as h, it as i, getFn as j, suite as s, test as t, withTimeout as w };
@@ -1,6 +1,8 @@
1
1
  import require$$0 from 'tty';
2
2
  import { isPackageExists } from 'local-pkg';
3
3
  import path from 'path';
4
+ import { util } from 'chai';
5
+ import * as tinyspy from 'tinyspy';
4
6
 
5
7
  var picocolors = {exports: {}};
6
8
 
@@ -248,6 +250,330 @@ const index = {
248
250
  ..._path
249
251
  };
250
252
 
253
+ const spies = /* @__PURE__ */ new Set();
254
+ function spyOn(obj, method, accessType) {
255
+ const dictionary = {
256
+ get: "getter",
257
+ set: "setter"
258
+ };
259
+ const objMethod = accessType ? { [dictionary[accessType]]: method } : method;
260
+ const stub = tinyspy.spyOn(obj, objMethod);
261
+ return enhanceSpy(stub);
262
+ }
263
+ function enhanceSpy(spy) {
264
+ const stub = spy;
265
+ let implementation;
266
+ const instances = [];
267
+ const mockContext = {
268
+ get calls() {
269
+ return stub.calls;
270
+ },
271
+ get instances() {
272
+ return instances;
273
+ },
274
+ get invocationCallOrder() {
275
+ return [];
276
+ },
277
+ get results() {
278
+ return stub.results.map(([callType, value]) => {
279
+ const type = callType === "error" ? "throw" : "return";
280
+ return { type, value };
281
+ });
282
+ }
283
+ };
284
+ let onceImplementations = [];
285
+ let name = "";
286
+ Object.defineProperty(stub, "name", {
287
+ get: () => name
288
+ });
289
+ stub.getMockName = () => name || "vi.fn()";
290
+ stub.mockName = (n) => {
291
+ name = n;
292
+ return stub;
293
+ };
294
+ stub.mockClear = () => {
295
+ stub.reset();
296
+ return stub;
297
+ };
298
+ stub.mockReset = () => {
299
+ stub.reset();
300
+ implementation = () => void 0;
301
+ onceImplementations = [];
302
+ return stub;
303
+ };
304
+ stub.mockRestore = () => {
305
+ stub.mockReset();
306
+ implementation = void 0;
307
+ return stub;
308
+ };
309
+ stub.getMockImplementation = () => implementation;
310
+ stub.mockImplementation = (fn2) => {
311
+ implementation = fn2;
312
+ return stub;
313
+ };
314
+ stub.mockImplementationOnce = (fn2) => {
315
+ onceImplementations.push(fn2);
316
+ return stub;
317
+ };
318
+ stub.mockReturnThis = () => stub.mockImplementation(function() {
319
+ return this;
320
+ });
321
+ stub.mockReturnValue = (val) => stub.mockImplementation(() => val);
322
+ stub.mockReturnValueOnce = (val) => stub.mockImplementationOnce(() => val);
323
+ stub.mockResolvedValue = (val) => stub.mockImplementation(() => Promise.resolve(val));
324
+ stub.mockResolvedValueOnce = (val) => stub.mockImplementationOnce(() => Promise.resolve(val));
325
+ stub.mockRejectedValue = (val) => stub.mockImplementation(() => Promise.reject(val));
326
+ stub.mockRejectedValueOnce = (val) => stub.mockImplementationOnce(() => Promise.reject(val));
327
+ util.addProperty(stub, "mock", () => mockContext);
328
+ stub.willCall(function(...args) {
329
+ instances.push(this);
330
+ const impl = onceImplementations.shift() || implementation || stub.getOriginal() || (() => {
331
+ });
332
+ return impl.apply(this, args);
333
+ });
334
+ spies.add(stub);
335
+ return stub;
336
+ }
337
+ function fn(implementation) {
338
+ return enhanceSpy(tinyspy.spyOn({ fn: implementation || (() => {
339
+ }) }, "fn"));
340
+ }
341
+
342
+ const originalSetTimeout = global.setTimeout;
343
+ const originalSetInterval = global.setInterval;
344
+ const originalClearTimeout = global.clearTimeout;
345
+ const originalClearInterval = global.clearInterval;
346
+ const MAX_LOOPS = 1e4;
347
+ const assertEvery = (assertions, message) => {
348
+ if (assertions.some((a) => !a))
349
+ throw new Error(message);
350
+ };
351
+ const assertMaxLoop = (times) => {
352
+ if (times >= MAX_LOOPS)
353
+ throw new Error("setTimeout/setInterval called 10 000 times. It's possible it stuck in an infinite loop.");
354
+ };
355
+ const getNodeTimeout = (id) => {
356
+ const timer = {
357
+ ref: () => timer,
358
+ unref: () => timer,
359
+ hasRef: () => true,
360
+ refresh: () => timer,
361
+ [Symbol.toPrimitive]: () => id
362
+ };
363
+ return timer;
364
+ };
365
+ class FakeTimers {
366
+ constructor() {
367
+ this._advancedTime = 0;
368
+ this._nestedTime = {};
369
+ this._scopeId = 0;
370
+ this._isNested = false;
371
+ this._isOnlyPending = false;
372
+ this._spyid = 0;
373
+ this._isMocked = false;
374
+ this._tasksQueue = [];
375
+ this._queueCount = 0;
376
+ }
377
+ useFakeTimers() {
378
+ this._isMocked = true;
379
+ this.reset();
380
+ const spyFactory = (spyType, resultBuilder) => {
381
+ return (cb, ms = 0) => {
382
+ const id = ++this._spyid;
383
+ const nestedTo = Object.entries(this._nestedTime).filter(([key]) => Number(key) <= this._scopeId);
384
+ const nestedMs = nestedTo.reduce((total, [, ms2]) => total + ms2, ms);
385
+ const call = { id, cb, ms, nestedMs, scopeId: this._scopeId };
386
+ const task = { type: spyType, call, nested: this._isNested };
387
+ this.pushTask(task);
388
+ return resultBuilder(id, cb);
389
+ };
390
+ };
391
+ this._setTimeout = spyOn(global, "setTimeout").mockImplementation(spyFactory("timeout" /* Timeout */, getNodeTimeout));
392
+ this._setInterval = spyOn(global, "setInterval").mockImplementation(spyFactory("interval" /* Interval */, getNodeTimeout));
393
+ const clearTimerFactory = (spyType) => (id) => {
394
+ if (id === void 0)
395
+ return;
396
+ const index = this._tasksQueue.findIndex(({ call, type }) => type === spyType && call.id === Number(id));
397
+ if (index !== -1)
398
+ this._tasksQueue.splice(index, 1);
399
+ };
400
+ this._clearTimeout = spyOn(global, "clearTimeout").mockImplementation(clearTimerFactory("timeout" /* Timeout */));
401
+ this._clearInterval = spyOn(global, "clearInterval").mockImplementation(clearTimerFactory("interval" /* Interval */));
402
+ }
403
+ useRealTimers() {
404
+ this._isMocked = false;
405
+ this.reset();
406
+ global.setTimeout = originalSetTimeout;
407
+ global.setInterval = originalSetInterval;
408
+ global.clearTimeout = originalClearTimeout;
409
+ global.clearInterval = originalClearInterval;
410
+ }
411
+ runOnlyPendingTimers() {
412
+ this.assertMocked();
413
+ this._isOnlyPending = true;
414
+ this.runQueue();
415
+ }
416
+ runAllTimers() {
417
+ this.assertMocked();
418
+ this.runQueue();
419
+ }
420
+ advanceTimersByTime(ms) {
421
+ this.assertMocked();
422
+ this._advancedTime += ms;
423
+ this.runQueue();
424
+ }
425
+ advanceTimersToNextTimer() {
426
+ this.assertMocked();
427
+ this.callQueueItem(0);
428
+ }
429
+ getTimerCount() {
430
+ this.assertMocked();
431
+ return this._tasksQueue.length;
432
+ }
433
+ reset() {
434
+ var _a, _b, _c, _d;
435
+ this._advancedTime = 0;
436
+ this._nestedTime = {};
437
+ this._isNested = false;
438
+ this._isOnlyPending = false;
439
+ this._spyid = 0;
440
+ this._queueCount = 0;
441
+ this._tasksQueue = [];
442
+ (_a = this._clearInterval) == null ? void 0 : _a.mockRestore();
443
+ (_b = this._clearTimeout) == null ? void 0 : _b.mockRestore();
444
+ (_c = this._setInterval) == null ? void 0 : _c.mockRestore();
445
+ (_d = this._setTimeout) == null ? void 0 : _d.mockRestore();
446
+ }
447
+ callQueueItem(index) {
448
+ var _a, _b;
449
+ const task = this._tasksQueue[index];
450
+ if (!task)
451
+ return;
452
+ const { call, type } = task;
453
+ this._scopeId = call.id;
454
+ this._isNested = true;
455
+ (_a = this._nestedTime)[_b = call.id] ?? (_a[_b] = 0);
456
+ this._nestedTime[call.id] += call.ms;
457
+ if (type === "timeout") {
458
+ this.removeTask(index);
459
+ } else if (type === "interval") {
460
+ call.nestedMs += call.ms;
461
+ const nestedMs = call.nestedMs;
462
+ const closestTask = this._tasksQueue.findIndex(({ type: type2, call: call2 }) => type2 === "interval" && call2.nestedMs < nestedMs);
463
+ if (closestTask !== -1 && closestTask !== index)
464
+ this.ensureQueueOrder();
465
+ }
466
+ call.cb();
467
+ this._queueCount++;
468
+ }
469
+ runQueue() {
470
+ let index = 0;
471
+ while (this._tasksQueue[index]) {
472
+ assertMaxLoop(this._queueCount);
473
+ const { call, nested } = this._tasksQueue[index];
474
+ if (this._advancedTime && call.nestedMs > this._advancedTime)
475
+ break;
476
+ if (this._isOnlyPending && nested) {
477
+ index++;
478
+ continue;
479
+ }
480
+ this.callQueueItem(index);
481
+ }
482
+ }
483
+ removeTask(index) {
484
+ if (index === 0)
485
+ this._tasksQueue.shift();
486
+ else
487
+ this._tasksQueue.splice(index, 1);
488
+ }
489
+ pushTask(task) {
490
+ this._tasksQueue.push(task);
491
+ this.ensureQueueOrder();
492
+ }
493
+ ensureQueueOrder() {
494
+ this._tasksQueue.sort((t1, t2) => {
495
+ const diff = t1.call.nestedMs - t2.call.nestedMs;
496
+ if (diff === 0) {
497
+ if (t1.type === "immediate" /* Immediate */ && t2.type !== "immediate" /* Immediate */)
498
+ return 1;
499
+ return 0;
500
+ }
501
+ return diff;
502
+ });
503
+ }
504
+ assertMocked() {
505
+ assertEvery([
506
+ this._isMocked,
507
+ this._setTimeout,
508
+ this._setInterval,
509
+ this._clearTimeout,
510
+ this._clearInterval
511
+ ], 'timers are not mocked. try calling "vitest.useFakeTimers()" first');
512
+ }
513
+ }
514
+
515
+ class VitestUtils {
516
+ constructor() {
517
+ this.spyOn = spyOn;
518
+ this.fn = fn;
519
+ this._timers = new FakeTimers();
520
+ }
521
+ useFakeTimers() {
522
+ return this._timers.useFakeTimers();
523
+ }
524
+ useRealTimers() {
525
+ return this._timers.useRealTimers();
526
+ }
527
+ runOnlyPendingTimers() {
528
+ return this._timers.runOnlyPendingTimers();
529
+ }
530
+ runAllTimers() {
531
+ return this._timers.runAllTimers();
532
+ }
533
+ advanceTimersByTime(ms) {
534
+ return this._timers.advanceTimersByTime(ms);
535
+ }
536
+ advanceTimersToNextTimer() {
537
+ return this._timers.advanceTimersToNextTimer();
538
+ }
539
+ getTimerCount() {
540
+ return this._timers.getTimerCount();
541
+ }
542
+ mock(path) {
543
+ }
544
+ unmock(path) {
545
+ }
546
+ async importActual(path) {
547
+ return {};
548
+ }
549
+ async importMock(path) {
550
+ return {};
551
+ }
552
+ mocked(item, _deep = false) {
553
+ return item;
554
+ }
555
+ isMockFunction(fn2) {
556
+ return typeof fn2 === "function" && "__isSpy" in fn2 && fn2.__isSpy;
557
+ }
558
+ clearAllMocks() {
559
+ __vitest__clearMocks__({ clearMocks: true });
560
+ spies.forEach((spy) => spy.mockClear());
561
+ return this;
562
+ }
563
+ resetAllMocks() {
564
+ __vitest__clearMocks__({ mockReset: true });
565
+ spies.forEach((spy) => spy.mockReset());
566
+ return this;
567
+ }
568
+ restoreAllMocks() {
569
+ __vitest__clearMocks__({ restoreMocks: true });
570
+ spies.forEach((spy) => spy.mockRestore());
571
+ return this;
572
+ }
573
+ }
574
+ const vitest = new VitestUtils();
575
+ const vi = vitest;
576
+
251
577
  function toArray(array) {
252
578
  array = array || [];
253
579
  if (Array.isArray(array))
@@ -260,6 +586,9 @@ function notNullish(v) {
260
586
  function slash(str) {
261
587
  return str.replace(/\\/g, "/");
262
588
  }
589
+ function mergeSlashes(str) {
590
+ return str.replace(/\/\//g, "/");
591
+ }
263
592
  const noop = () => {
264
593
  };
265
594
  function partitionSuiteChildren(suite) {
@@ -323,7 +652,7 @@ function getNames(task) {
323
652
  }
324
653
  return names;
325
654
  }
326
- async function ensurePackageInstalled(dependency, promptInstall = !process.env.CI) {
655
+ async function ensurePackageInstalled(dependency, promptInstall = !process.env.CI && process.stdout.isTTY) {
327
656
  if (isPackageExists(dependency))
328
657
  return true;
329
658
  console.log(c.red(`${c.inverse(c.red(" MISSING DEP "))} Can not find dependency '${dependency}'
@@ -342,5 +671,14 @@ async function ensurePackageInstalled(dependency, promptInstall = !process.env.C
342
671
  }
343
672
  return false;
344
673
  }
674
+ function clearModuleMocks() {
675
+ const { clearMocks, mockReset, restoreMocks } = process.__vitest_worker__.config;
676
+ if (restoreMocks)
677
+ vi.restoreAllMocks();
678
+ else if (mockReset)
679
+ vi.resetAllMocks();
680
+ else if (clearMocks)
681
+ vi.clearAllMocks();
682
+ }
345
683
 
346
- export { getTests as a, basename as b, c, dirname as d, ensurePackageInstalled as e, getSuites as f, getNames as g, resolve as h, isAbsolute as i, hasFailed as j, notNullish as k, index as l, interpretOnlyMode as m, noop as n, hasTests as o, partitionSuiteChildren as p, getTasks as q, relative as r, slash as s, toArray as t };
684
+ export { getTasks as A, spyOn as a, vi as b, c, slash as d, ensurePackageInstalled as e, fn as f, getNames as g, getTests as h, isAbsolute as i, dirname as j, basename as k, getSuites as l, resolve as m, noop as n, hasFailed as o, notNullish as p, mergeSlashes as q, relative as r, spies as s, toArray as t, index as u, vitest as v, interpretOnlyMode as w, partitionSuiteChildren as x, hasTests as y, clearModuleMocks as z };
package/dist/utils.js CHANGED
@@ -1,4 +1,6 @@
1
- export { e as ensurePackageInstalled, g as getNames, f as getSuites, q as getTasks, a as getTests, j as hasFailed, o as hasTests, m as interpretOnlyMode, n as noop, k as notNullish, p as partitionSuiteChildren, h as resolvePath, s as slash, t as toArray } from './utils-b780070b.js';
1
+ export { z as clearModuleMocks, e as ensurePackageInstalled, g as getNames, l as getSuites, A as getTasks, h as getTests, o as hasFailed, y as hasTests, w as interpretOnlyMode, q as mergeSlashes, n as noop, p as notNullish, x as partitionSuiteChildren, m as resolvePath, d as slash, t as toArray } from './utils-49e5008c.js';
2
2
  import 'local-pkg';
3
3
  import 'tty';
4
4
  import 'path';
5
+ import 'chai';
6
+ import 'tinyspy';