vitest 0.0.109 → 0.0.110

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7242,23 +7242,27 @@ const spinnerMap = /* @__PURE__ */ new WeakMap();
7242
7242
  const outputMap = /* @__PURE__ */ new WeakMap();
7243
7243
  const pointer = c.yellow(F_POINTER);
7244
7244
  const skipped = c.yellow(F_DOWN);
7245
- function divider(text, left, right) {
7245
+ function getCols(delta = 0) {
7246
7246
  let length = process.stdout.columns;
7247
7247
  if (!length || isNaN(length))
7248
- length = 10;
7248
+ length = 30;
7249
+ return Math.max(length + delta, 0);
7250
+ }
7251
+ function divider(text, left, right) {
7252
+ const cols = getCols();
7249
7253
  if (text) {
7250
7254
  const textLength = stripAnsi(text).length;
7251
7255
  if (left == null && right != null) {
7252
- left = length - textLength - right;
7256
+ left = cols - textLength - right;
7253
7257
  } else {
7254
- left = left ?? Math.floor((length - textLength) / 2);
7255
- right = length - textLength - left;
7258
+ left = left ?? Math.floor((cols - textLength) / 2);
7259
+ right = cols - textLength - left;
7256
7260
  }
7257
7261
  left = Math.max(0, left);
7258
7262
  right = Math.max(0, right);
7259
7263
  return `${F_LONG_DASH.repeat(left)}${text}${F_LONG_DASH.repeat(right)}`;
7260
7264
  }
7261
- return F_LONG_DASH.repeat(length);
7265
+ return F_LONG_DASH.repeat(cols);
7262
7266
  }
7263
7267
  function formatTestPath(root, path) {
7264
7268
  var _a;
@@ -7344,6 +7348,15 @@ function getStateSymbol(task) {
7344
7348
  }
7345
7349
  return " ";
7346
7350
  }
7351
+ function formatFilepath(path) {
7352
+ const lastSlash = Math.max(path.lastIndexOf("/") + 1, 0);
7353
+ const basename2 = path.slice(lastSlash);
7354
+ let firstDot = basename2.indexOf(".");
7355
+ if (firstDot < 0)
7356
+ firstDot = basename2.length;
7357
+ firstDot += lastSlash;
7358
+ return c.dim(path.slice(0, lastSlash)) + path.slice(lastSlash, firstDot) + c.dim(path.slice(firstDot));
7359
+ }
7347
7360
  function renderTree(tasks, level = 0) {
7348
7361
  var _a, _b, _c, _d;
7349
7362
  let output = [];
@@ -7359,7 +7372,10 @@ function renderTree(tasks, level = 0) {
7359
7372
  if (duration > DURATION_LONG)
7360
7373
  suffix += c.yellow(` ${Math.round(duration)}${c.dim("ms")}`);
7361
7374
  }
7362
- output.push(" ".repeat(level) + prefix + task.name + suffix);
7375
+ let name = task.name;
7376
+ if (level === 0)
7377
+ name = formatFilepath(name);
7378
+ output.push(" ".repeat(level) + prefix + name + suffix);
7363
7379
  if (((_b = task.result) == null ? void 0 : _b.state) !== "pass" && outputMap.get(task) != null) {
7364
7380
  let data = outputMap.get(task);
7365
7381
  if (typeof data === "string") {
@@ -7369,7 +7385,7 @@ function renderTree(tasks, level = 0) {
7369
7385
  }
7370
7386
  if (data != null) {
7371
7387
  const out = `${" ".repeat(level)}${F_RIGHT} ${data}`;
7372
- output.push(` ${c.gray(cliTruncate(out, process.stdout.columns - 3))}`);
7388
+ output.push(` ${c.gray(cliTruncate(out, getCols(-3)))}`);
7373
7389
  }
7374
7390
  }
7375
7391
  if ((((_c = task.result) == null ? void 0 : _c.state) === "fail" || ((_d = task.result) == null ? void 0 : _d.state) === "run") && task.type === "suite" && task.tasks.length > 0)
@@ -8642,16 +8658,68 @@ MagicString.prototype.trimStart = function trimStart (charType) {
8642
8658
  return this;
8643
8659
  };
8644
8660
 
8645
- const mockRegexp = /\b(?:vitest|vi)\s*.\s*(mock|unmock|importActual|importMock)\(["`'\s](.*[@\w_-]+)["`'\s]\);?/mg;
8661
+ const mockRegexp = /\b((?:vitest|vi)\s*.\s*mock\(["`'\s](.*[@\w_-]+)["`'\s])[),]{1}/;
8662
+ const pathRegexp = /\b(?:vitest|vi)\s*.\s*(unmock|importActual|importMock)\(["`'\s](.*[@\w_-]+)["`'\s]\);?/mg;
8663
+ const isComment = (line) => {
8664
+ const commentStarts = ["//", "/*", "*"];
8665
+ line = line.trim();
8666
+ return commentStarts.some((cmt) => line.startsWith(cmt));
8667
+ };
8668
+ const parseMocks = (code) => {
8669
+ const splitted = code.split("\n");
8670
+ const mockCalls = {};
8671
+ let mockCall = 0;
8672
+ let lineIndex = -1;
8673
+ while (lineIndex < splitted.length) {
8674
+ lineIndex++;
8675
+ const line = splitted[lineIndex];
8676
+ if (!line)
8677
+ break;
8678
+ const mock = mockCalls[mockCall] || {
8679
+ code: "",
8680
+ declaraton: "",
8681
+ path: ""
8682
+ };
8683
+ if (!mock.code) {
8684
+ const started = mockRegexp.exec(line);
8685
+ if (!started || isComment(line))
8686
+ continue;
8687
+ mock.code += `${line}
8688
+ `;
8689
+ mock.declaraton = started[1];
8690
+ mock.path = started[2];
8691
+ mockCalls[mockCall] = mock;
8692
+ if (line.includes(");")) {
8693
+ mockCall++;
8694
+ continue;
8695
+ }
8696
+ continue;
8697
+ }
8698
+ mock.code += `${line}
8699
+ `;
8700
+ mockCalls[mockCall] = mock;
8701
+ const startNumber = (mock.code.match(/{/g) || []).length;
8702
+ const endNumber = (mock.code.match(/}/g) || []).length;
8703
+ if (line.includes(");")) {
8704
+ if (startNumber === endNumber || startNumber === 0 && endNumber === 0)
8705
+ mockCall++;
8706
+ }
8707
+ }
8708
+ return Object.values(mockCalls);
8709
+ };
8710
+ const getMethodCall = (method, actualPath, importPath) => {
8711
+ let nodeModule = "null";
8712
+ if (actualPath.includes("/node_modules/"))
8713
+ nodeModule = `"${importPath}"`;
8714
+ return `__vitest__${method}__("${actualPath}", ${nodeModule}`;
8715
+ };
8646
8716
  const MocksPlugin = () => {
8647
8717
  return {
8648
8718
  name: "vitest:mock-plugin",
8649
8719
  enforce: "post",
8650
8720
  async transform(code, id) {
8651
8721
  let m;
8652
- const matchAll = Array.from(code.matchAll(mockRegexp));
8653
- if (!matchAll.length)
8654
- return;
8722
+ const matchAll = code.matchAll(pathRegexp);
8655
8723
  for (const match of matchAll) {
8656
8724
  const [line, method, modulePath] = match;
8657
8725
  const filepath = await this.resolve(modulePath, id);
@@ -8659,18 +8727,19 @@ const MocksPlugin = () => {
8659
8727
  m ?? (m = new MagicString(code));
8660
8728
  const start = match.index || 0;
8661
8729
  const end = start + line.length;
8662
- let nodeModule = "null";
8663
- if (filepath.id.includes("/node_modules/"))
8664
- nodeModule = `"${modulePath}"`;
8665
- const overwrite = `__vitest__${method}__("${filepath.id}", ${nodeModule});`;
8666
- if (method === "mock") {
8667
- m.prepend(`${overwrite}
8668
-
8669
- `);
8670
- m.remove(start, end);
8671
- } else {
8672
- m.overwrite(start, end, overwrite);
8673
- }
8730
+ const overwrite = `${getMethodCall(method, filepath.id, modulePath)});`;
8731
+ m.overwrite(start, end, overwrite);
8732
+ }
8733
+ }
8734
+ if (mockRegexp.exec(code)) {
8735
+ const mocks = parseMocks((m == null ? void 0 : m.toString()) || code);
8736
+ for (const mock of mocks) {
8737
+ const filepath = await this.resolve(mock.path, id);
8738
+ if (!filepath)
8739
+ continue;
8740
+ m ?? (m = new MagicString(code));
8741
+ const overwrite = getMethodCall("mock", filepath.id, mock.path);
8742
+ m.prepend(mock.code.replace(mock.declaraton, overwrite));
8674
8743
  }
8675
8744
  }
8676
8745
  if (m) {
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Formatter } from 'picocolors/types';
2
2
  import { OptionsReceived } from 'pretty-format';
3
3
  import { MessagePort } from 'worker_threads';
4
- export { assert, default as chai, expect, should } from 'chai';
5
4
  export { Spy, SpyFn } from 'tinyspy';
5
+ export { assert, default as chai, should } from 'chai';
6
6
 
7
7
  declare const EXPECTED_COLOR: Formatter;
8
8
  declare const RECEIVED_COLOR: Formatter;
@@ -117,6 +117,7 @@ interface AsymmetricMatcherInterface {
117
117
  declare abstract class AsymmetricMatcher<T, State extends MatcherState = MatcherState> implements AsymmetricMatcherInterface {
118
118
  protected sample: T;
119
119
  protected inverse: boolean;
120
+ $$typeof: symbol;
120
121
  constructor(sample: T, inverse?: boolean);
121
122
  protected getMatcherContext(): State;
122
123
  abstract asymmetricMatch(other: unknown): boolean;
@@ -528,6 +529,8 @@ declare const afterAll: (fn: SuiteHooks['afterAll'][0], timeout?: number | undef
528
529
  declare const beforeEach: (fn: SuiteHooks['beforeEach'][0], timeout?: number | undefined) => void;
529
530
  declare const afterEach: (fn: SuiteHooks['afterEach'][0], timeout?: number | undefined) => void;
530
531
 
532
+ declare const expect: (value: any, message?: string | undefined) => Chai.Assertion;
533
+
531
534
  interface MockResultReturn<T> {
532
535
  type: 'return';
533
536
  value: T;
@@ -620,10 +623,60 @@ declare class VitestUtils {
620
623
  getMockedDate(): string | number | Date | null;
621
624
  spyOn: typeof spyOn;
622
625
  fn: typeof fn;
623
- mock(path: string): void;
626
+ /**
627
+ * Makes all `imports` to passed module to be mocked.
628
+ * - If there is a factory, will return it's result. The call to `vi.mock` is hoisted to the top of the file,
629
+ * so you don't have access to variables declared in the global file scope, if you didn't put them before imports!
630
+ * - If `__mocks__` folder with file of the same name exist, all imports will
631
+ * return it.
632
+ * - If there is no `__mocks__` folder or a file with the same name inside, will call original
633
+ * module and mock it.
634
+ * @param path Path to the module. Can be aliased, if your config suppors it
635
+ * @param factory Factory for the mocked module. Has the highest priority.
636
+ */
637
+ mock(path: string, factory?: () => any): void;
638
+ /**
639
+ * Removes module from mocked registry. All subsequent calls to import will
640
+ * return original module even if it was mocked.
641
+ * @param path Path to the module. Can be aliased, if your config suppors it
642
+ */
624
643
  unmock(path: string): void;
644
+ /**
645
+ * Imports module, bypassing all checks if it should be mocked.
646
+ * Can be useful if you want to mock module partially.
647
+ * @example
648
+ * vi.mock('./example', async () => {
649
+ * const axios = await vi.importActual('./example')
650
+ *
651
+ * return { ...axios, get: vi.fn() }
652
+ * })
653
+ * @param path Path to the module. Can be aliased, if your config suppors it
654
+ * @returns Actual module without spies
655
+ */
625
656
  importActual<T>(path: string): Promise<T>;
626
- importMock<T>(path: string): Promise<T>;
657
+ /**
658
+ * Imports a module with all of its properties and nested properties mocked.
659
+ * For the rules applied, see docs.
660
+ * @param path Path to the module. Can be aliased, if your config suppors it
661
+ * @returns Fully mocked module
662
+ */
663
+ importMock<T>(path: string): Promise<MaybeMockedDeep<T>>;
664
+ /**
665
+ * Type helpers for TypeScript. In reality just returns the object that was passed.
666
+ * @example
667
+ * import example from './example'
668
+ * vi.mock('./example')
669
+ *
670
+ * test('1+1 equals 2' async () => {
671
+ * vi.mocked(example.calc).mockRestore()
672
+ *
673
+ * const res = example.calc(1, '+', 1)
674
+ *
675
+ * expect(res).toBe(2)
676
+ * })
677
+ * @param item Anything that can be mocked
678
+ * @param deep If the object is deeply mocked
679
+ */
627
680
  mocked<T>(item: T, deep?: false): MaybeMocked<T>;
628
681
  mocked<T>(item: T, deep: true): MaybeMockedDeep<T>;
629
682
  isMockFunction(fn: any): any;
@@ -654,6 +707,7 @@ declare global {
654
707
  any(constructor: unknown): Any;
655
708
  arrayContaining(expected: any): ArrayContaining;
656
709
  stringMatching(expected: RegExp): StringMatching;
710
+ assertions(expected: number): void;
657
711
  }
658
712
  interface Assertion {
659
713
  chaiEqual(expected: any): void;
@@ -708,4 +762,4 @@ declare global {
708
762
  }
709
763
  }
710
764
 
711
- export { ArgumentsOf, ArgumentsType, Arrayable, Awaitable, BuiltinEnvironment, ComputeMode, ConstructorArgumentsOf, DoneCallback, Environment, EnvironmentReturn, File, HookListener, InlineConfig, JestMockCompat, JestMockCompatContext, JestMockCompatFn, MaybeMocked, MaybeMockedConstructor, MaybeMockedDeep, MethodKeysOf, MockWithArgs, MockableFunction, MockedFunction, MockedFunctionDeep, MockedObject, MockedObjectDeep, ModuleCache, Nullable, PropertyKeysOf, Reporter, ResolvedConfig, RpcCall, RpcMap, RpcPayload, RpcSend, RunMode, RuntimeContext, SnapshotData, SnapshotMatchOptions, SnapshotResult, SnapshotStateOptions, SnapshotSummary, SnapshotUpdateState, Suite, SuiteCollector, SuiteHooks, Task, TaskBase, TaskResult, TaskResultPack, TaskState, Test, TestCollector, TestFactory, TestFunction, UncheckedSnapshot, UserConfig, UserConsoleLog, WorkerContext, afterAll, afterEach, beforeAll, beforeEach, describe, fn, it, spies, spyOn, suite, test, vi, vitest };
765
+ export { ArgumentsOf, ArgumentsType, Arrayable, Awaitable, BuiltinEnvironment, ComputeMode, ConstructorArgumentsOf, DoneCallback, Environment, EnvironmentReturn, File, HookListener, InlineConfig, JestMockCompat, JestMockCompatContext, JestMockCompatFn, MaybeMocked, MaybeMockedConstructor, MaybeMockedDeep, MethodKeysOf, MockWithArgs, MockableFunction, MockedFunction, MockedFunctionDeep, MockedObject, MockedObjectDeep, ModuleCache, Nullable, PropertyKeysOf, Reporter, ResolvedConfig, RpcCall, RpcMap, RpcPayload, RpcSend, RunMode, RuntimeContext, SnapshotData, SnapshotMatchOptions, SnapshotResult, SnapshotStateOptions, SnapshotSummary, SnapshotUpdateState, Suite, SuiteCollector, SuiteHooks, Task, TaskBase, TaskResult, TaskResultPack, TaskState, Test, TestCollector, TestFactory, TestFunction, UncheckedSnapshot, UserConfig, UserConsoleLog, WorkerContext, afterAll, afterEach, beforeAll, beforeEach, describe, expect, fn, it, spies, spyOn, suite, test, vi, vitest };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- export { d as describe, i as it, s as suite, t as test, b as vi, v as vitest } from './vi-9754296d.js';
2
- export { a as afterAll, d as afterEach, b as beforeAll, c as beforeEach } from './index-0961cf69.js';
3
- export { assert, default as chai, expect, should } from 'chai';
4
- export { f as fn, s as spies, a as spyOn } from './jest-mock-8498c46d.js';
1
+ export { d as describe, i as it, c as suite, t as test, e as vi, v as vitest } from './vi-aedc8539.js';
2
+ export { a as afterAll, d as afterEach, b as beforeAll, c as beforeEach, e as expect } from './index-a90f376d.js';
3
+ export { f as fn, s as spies, a as spyOn } from './jest-mock-a57b745c.js';
4
+ export { assert, default as chai, should } from 'chai';
5
5
  import './utils-d97bd6d9.js';
6
6
  import 'tty';
7
7
  import 'local-pkg';
@@ -44,10 +44,7 @@ function enhanceSpy(spy) {
44
44
  }
45
45
  };
46
46
  let onceImplementations = [];
47
- let name = "";
48
- Object.defineProperty(stub, "name", {
49
- get: () => name
50
- });
47
+ let name = stub.name;
51
48
  stub.getMockName = () => name || "vi.fn()";
52
49
  stub.mockName = (n) => {
53
50
  name = n;
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
- export { c as createVitest } from './index-a727b58c.js';
1
+ export { c as createVitest } from './index-b183bb20.js';
2
2
  import './utils-d97bd6d9.js';
3
3
  import 'tty';
4
4
  import 'local-pkg';