vitest 0.0.89 → 0.0.93

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.
package/dist/index.d.ts CHANGED
@@ -108,6 +108,50 @@ declare type MatchersObject<T extends MatcherState = MatcherState> = {
108
108
  [id: string]: RawMatcherFn<T>;
109
109
  };
110
110
 
111
+ interface AsymmetricMatcherInterface {
112
+ asymmetricMatch(other: unknown): boolean;
113
+ toString(): string;
114
+ getExpectedType?(): string;
115
+ toAsymmetricMatcher?(): string;
116
+ }
117
+ declare abstract class AsymmetricMatcher<T, State extends MatcherState = MatcherState> implements AsymmetricMatcherInterface {
118
+ protected sample: T;
119
+ protected inverse: boolean;
120
+ constructor(sample: T, inverse?: boolean);
121
+ protected getMatcherContext(): State;
122
+ abstract asymmetricMatch(other: unknown): boolean;
123
+ abstract toString(): string;
124
+ getExpectedType?(): string;
125
+ toAsymmetricMatcher?(): string;
126
+ }
127
+ declare class Anything extends AsymmetricMatcher<void> {
128
+ asymmetricMatch(other: unknown): boolean;
129
+ toString(): string;
130
+ toAsymmetricMatcher(): string;
131
+ }
132
+ declare class ObjectContaining extends AsymmetricMatcher<Record<string, unknown>> {
133
+ constructor(sample: Record<string, unknown>, inverse?: boolean);
134
+ getPrototype(obj: object): any;
135
+ hasProperty(obj: object | null, property: string): boolean;
136
+ asymmetricMatch(other: any): boolean;
137
+ toString(): string;
138
+ getExpectedType(): string;
139
+ }
140
+ declare class ArrayContaining extends AsymmetricMatcher<Array<unknown>> {
141
+ constructor(sample: Array<unknown>, inverse?: boolean);
142
+ asymmetricMatch(other: Array<unknown>): boolean;
143
+ toString(): string;
144
+ getExpectedType(): string;
145
+ }
146
+ declare class Any extends AsymmetricMatcher<any> {
147
+ constructor(sample: unknown);
148
+ fnNameFor(func: Function): string;
149
+ asymmetricMatch(other: unknown): boolean;
150
+ toString(): string;
151
+ getExpectedType(): string;
152
+ toAsymmetricMatcher(): string;
153
+ }
154
+
111
155
  declare type Awaitable<T> = T | PromiseLike<T>;
112
156
  declare type Nullable<T> = T | null | undefined;
113
157
  declare type Arrayable<T> = T | Array<T>;
@@ -269,6 +313,7 @@ interface SnapshotSummary {
269
313
  updated: number;
270
314
  }
271
315
 
316
+ declare type BuiltinEnvironment = 'node' | 'jsdom' | 'happy-dom';
272
317
  interface InlineConfig {
273
318
  /**
274
319
  * Include globs for test files
@@ -314,7 +359,7 @@ interface InlineConfig {
314
359
  *
315
360
  * @default 'node'
316
361
  */
317
- environment?: 'node' | 'jsdom' | 'happy-dom';
362
+ environment?: BuiltinEnvironment;
318
363
  /**
319
364
  * Update snapshot files
320
365
  *
@@ -572,8 +617,8 @@ interface JestMockCompat<TArgs extends any[] = any[], TReturns = any> {
572
617
  mockReturnThis(): this;
573
618
  mockReturnValue(obj: TReturns): this;
574
619
  mockReturnValueOnce(obj: TReturns): this;
575
- mockResolvedValue(obj: Unpromisify<TReturns>): this;
576
- mockResolvedValueOnce(obj: Unpromisify<TReturns>): this;
620
+ mockResolvedValue(obj: Awaited<TReturns>): this;
621
+ mockResolvedValueOnce(obj: Awaited<TReturns>): this;
577
622
  mockRejectedValue(obj: any): this;
578
623
  mockRejectedValueOnce(obj: any): this;
579
624
  }
@@ -581,14 +626,29 @@ interface JestMockCompatFn<TArgs extends any[] = any, TReturns = any> extends Je
581
626
  (...args: TArgs): TReturns;
582
627
  }
583
628
  declare function spyOn<T, K extends keyof T>(obj: T, method: K, accessType?: 'get' | 'set'): T[K] extends (...args: infer TArgs) => infer TReturnValue ? JestMockCompat<TArgs, TReturnValue> : JestMockCompat;
584
- declare type Unpromisify<T> = T extends Promise<infer R> ? R : never;
629
+ declare type Awaited<T> = T extends Promise<infer R> ? R : never;
585
630
  declare function fn<TArgs extends any[] = any[], R = any>(): JestMockCompatFn<TArgs, R>;
586
631
  declare function fn<TArgs extends any[] = any[], R = any>(implementation: (...args: TArgs) => R): JestMockCompatFn<TArgs, R>;
587
632
 
588
- declare const vitest: {
633
+ declare class VitestUtils {
589
634
  spyOn: typeof spyOn;
590
635
  fn: typeof fn;
591
- };
636
+ mock: (path: string) => string;
637
+ private _timers;
638
+ constructor();
639
+ useFakeTimers(): void;
640
+ useRealTimers(): void;
641
+ runOnlyPendingTimers(): void;
642
+ runAllTimers(): void;
643
+ advanceTimersByTime(ms: number): void;
644
+ advanceTimersToNextTimer(): void;
645
+ runAllTicks(): void;
646
+ setSystemTime(time?: number | Date): void;
647
+ getRealSystemTime(): number;
648
+ getTimerCount(): number;
649
+ }
650
+ declare const vitest: VitestUtils;
651
+ declare const vi: VitestUtils;
592
652
 
593
653
  declare module 'vite' {
594
654
  interface UserConfig {
@@ -602,8 +662,14 @@ declare global {
602
662
  namespace Chai {
603
663
  interface ExpectStatic {
604
664
  extend(expects: MatchersObject): void;
665
+ stringContaining(expected: string): void;
666
+ anything(): Anything;
667
+ objectContaining(expected: any): ObjectContaining;
668
+ any(constructor: unknown): Any;
669
+ arrayContaining(expected: any): ArrayContaining;
605
670
  }
606
671
  interface Assertion {
672
+ chaiEqual(expected: any): void;
607
673
  toMatchSnapshot(message?: string): Assertion;
608
674
  toMatchInlineSnapshot(snapshot?: string, message?: string): Assertion;
609
675
  matchSnapshot(message?: string): Assertion;
@@ -655,4 +721,4 @@ declare global {
655
721
  }
656
722
  }
657
723
 
658
- export { ArgumentsType, Arrayable, Awaitable, ComputeMode, DoneCallback, Environment, EnvironmentReturn, File, HookListener, InlineConfig, ModuleCache, Nullable, 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, it, suite, test, vitest };
724
+ export { ArgumentsType, Arrayable, Awaitable, BuiltinEnvironment, ComputeMode, DoneCallback, Environment, EnvironmentReturn, File, HookListener, InlineConfig, ModuleCache, Nullable, 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, it, suite, test, vi, vitest };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { d as describe, i as it, s as suite, t as test } from './suite-b8c6cb53.js';
2
- export { a as afterAll, d as afterEach, b as beforeAll, c as beforeEach, v as vitest } from './index-722fb5a5.js';
2
+ export { a as afterAll, d as afterEach, b as beforeAll, c as beforeEach, e as vi, v as vitest } from './index-708135df.js';
3
3
  export { assert, default as chai, expect, should } from 'chai';
4
4
  export { spy, spyOn } from 'tinyspy';
5
5
  import './index-9e71c815.js';
@@ -0,0 +1,78 @@
1
+ import { A as API_PATH } from './constants-9cfa4d7b.js';
2
+ import 'path';
3
+ import 'url';
4
+
5
+ /*! (c) 2020 Andrea Giammarchi */
6
+
7
+ const {parse: $parse, stringify: $stringify} = JSON;
8
+
9
+ const Primitive = String; // it could be Number
10
+ const primitive = 'string'; // it could be 'number'
11
+ const object = 'object';
12
+
13
+ const noop = (_, value) => value;
14
+
15
+ const set = (known, input, value) => {
16
+ const index = Primitive(input.push(value) - 1);
17
+ known.set(value, index);
18
+ return index;
19
+ };
20
+
21
+ const stringify = (value, replacer, space) => {
22
+ const $ = replacer && typeof replacer === object ?
23
+ (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) :
24
+ (replacer || noop);
25
+ const known = new Map;
26
+ const input = [];
27
+ const output = [];
28
+ let i = +set(known, input, $.call({'': value}, '', value));
29
+ let firstRun = !i;
30
+ while (i < input.length) {
31
+ firstRun = true;
32
+ output[i] = $stringify(input[i++], replace, space);
33
+ }
34
+ return '[' + output.join(',') + ']';
35
+ function replace(key, value) {
36
+ if (firstRun) {
37
+ firstRun = !firstRun;
38
+ return value;
39
+ }
40
+ const after = $.call(this, key, value);
41
+ switch (typeof after) {
42
+ case object:
43
+ if (after === null) return after;
44
+ case primitive:
45
+ return known.get(after) || set(known, input, after);
46
+ }
47
+ return after;
48
+ }
49
+ };
50
+
51
+ function sendFlatted(res, data) {
52
+ res.setHeader("Content-Type", "application/json");
53
+ res.write(stringify(data));
54
+ res.statusCode = 200;
55
+ res.end();
56
+ }
57
+ function middlewareAPI(ctx) {
58
+ return (req, res, next) => {
59
+ var _a;
60
+ if (!((_a = req.url) == null ? void 0 : _a.startsWith(API_PATH)))
61
+ return next();
62
+ const url = req.url.slice(API_PATH.length);
63
+ if (url === "/") {
64
+ return sendFlatted(res, {
65
+ files: ctx.state.filesMap
66
+ });
67
+ }
68
+ if (url === "/files") {
69
+ return sendFlatted(res, {
70
+ files: Object.keys(ctx.state.filesMap)
71
+ });
72
+ }
73
+ res.statusCode = 404;
74
+ res.end();
75
+ };
76
+ }
77
+
78
+ export { middlewareAPI as default, sendFlatted };
package/dist/node.js CHANGED
@@ -1,19 +1,20 @@
1
- export { c as createVitest } from './index-733e7378.js';
1
+ export { c as createVitest } from './index-880654a3.js';
2
2
  import 'path';
3
3
  import 'vite';
4
4
  import 'process';
5
5
  import 'fs';
6
- import './constants-adef7ffb.js';
6
+ import 'fast-glob';
7
+ import 'util';
8
+ import './constants-9cfa4d7b.js';
7
9
  import 'url';
8
- import './utils-385e2d09.js';
9
- import 'module';
10
+ import './utils-576876dc.js';
10
11
  import 'tty';
12
+ import 'local-pkg';
11
13
  import 'perf_hooks';
12
- import './error-309196c9.js';
14
+ import './error-bf2213e4.js';
13
15
  import 'source-map';
16
+ import './index-5cc247ff.js';
14
17
  import 'assert';
15
18
  import 'events';
16
19
  import 'worker_threads';
17
20
  import 'piscina';
18
- import 'fast-glob';
19
- import 'micromatch';
@@ -1,5 +1,5 @@
1
- import { createRequire } from 'module';
2
1
  import require$$0 from 'tty';
2
+ import { isPackageExists } from 'local-pkg';
3
3
 
4
4
  var picocolors = {exports: {}};
5
5
 
@@ -76,6 +76,8 @@ function notNullish(v) {
76
76
  function slash(str) {
77
77
  return str.replace(/\\/g, "/");
78
78
  }
79
+ const noop = () => {
80
+ };
79
81
  function partitionSuiteChildren(suite) {
80
82
  let tasksGroup = [];
81
83
  const tasksGroups = [];
@@ -91,15 +93,23 @@ function partitionSuiteChildren(suite) {
91
93
  tasksGroups.push(tasksGroup);
92
94
  return tasksGroups;
93
95
  }
94
- function interpretOnlyMode(items) {
95
- if (items.some((i) => i.mode === "only")) {
96
- items.forEach((i) => {
97
- if (i.mode === "run")
98
- i.mode = "skip";
99
- else if (i.mode === "only")
100
- i.mode = "run";
96
+ function interpretOnlyMode(tasks) {
97
+ if (tasks.some((t) => t.mode === "only")) {
98
+ tasks.forEach((t) => {
99
+ if (t.mode === "run")
100
+ t.mode = "skip";
101
+ else if (t.mode === "only")
102
+ t.mode = "run";
101
103
  });
102
104
  }
105
+ tasks.forEach((t) => {
106
+ if (t.type === "suite") {
107
+ if (t.mode === "skip")
108
+ t.tasks.forEach((c2) => c2.mode === "run" && (c2.mode = "skip"));
109
+ else
110
+ interpretOnlyMode(t.tasks);
111
+ }
112
+ });
103
113
  }
104
114
  function getTests(suite) {
105
115
  return toArray(suite).flatMap((s) => s.tasks.flatMap((c2) => c2.type === "test" ? [c2] : getTests(c2)));
@@ -129,15 +139,24 @@ function getNames(task) {
129
139
  }
130
140
  return names;
131
141
  }
132
- function checkPeerDependency(dependency) {
133
- const require = createRequire(import.meta.url);
134
- try {
135
- require.resolve(dependency);
136
- } catch {
137
- console.log(c.red(`${c.inverse(c.red(" MISSING DEP "))} Cound not find '${dependency}' peer dependency, please try installing it
142
+ async function ensurePackageInstalled(dependency, promptInstall = !process.env.CI) {
143
+ if (isPackageExists(dependency))
144
+ return true;
145
+ console.log(c.red(`${c.inverse(c.red(" MISSING DEP "))} Can not find dependency '${dependency}'
138
146
  `));
139
- process.exit(1);
147
+ if (!promptInstall)
148
+ return false;
149
+ const prompts = await import('./index-fa899e66.js').then(function (n) { return n.i; });
150
+ const { install } = await prompts.prompt({
151
+ type: "confirm",
152
+ name: "install",
153
+ message: c.reset(`Do you want to install ${c.green(dependency)}?`)
154
+ });
155
+ if (install) {
156
+ await (await import('./index-e7a421bb.js')).installPackage(dependency);
157
+ return true;
140
158
  }
159
+ return false;
141
160
  }
142
161
 
143
- export { getTests as a, getSuites as b, c, hasTests as d, getTasks as e, checkPeerDependency as f, getNames as g, hasFailed as h, interpretOnlyMode as i, notNullish as n, partitionSuiteChildren as p, slash as s, toArray as t };
162
+ export { getTests as a, getSuites as b, c, notNullish as d, ensurePackageInstalled as e, hasTests as f, getNames as g, hasFailed as h, interpretOnlyMode as i, getTasks as j, noop as n, partitionSuiteChildren as p, slash as s, toArray as t };
package/dist/utils.js CHANGED
@@ -1,3 +1,3 @@
1
- import 'module';
2
- export { f as checkPeerDependency, g as getNames, b as getSuites, e as getTasks, a as getTests, h as hasFailed, d as hasTests, i as interpretOnlyMode, n as notNullish, p as partitionSuiteChildren, s as slash, t as toArray } from './utils-385e2d09.js';
1
+ export { e as ensurePackageInstalled, g as getNames, b as getSuites, j as getTasks, a as getTests, h as hasFailed, f as hasTests, i as interpretOnlyMode, n as noop, d as notNullish, p as partitionSuiteChildren, s as slash, t as toArray } from './utils-576876dc.js';
2
+ import 'local-pkg';
3
3
  import 'tty';
package/dist/worker.js CHANGED
@@ -1,15 +1,16 @@
1
1
  import path, { resolve as resolve$3, dirname as dirname$3 } from 'path';
2
2
  import { n as nanoid } from './index-9e71c815.js';
3
- import { c as distDir } from './constants-adef7ffb.js';
3
+ import { c as distDir } from './constants-9cfa4d7b.js';
4
4
  import { builtinModules, createRequire } from 'module';
5
5
  import { pathToFileURL, fileURLToPath, URL as URL$1 } from 'url';
6
6
  import vm from 'vm';
7
- import { s as slash } from './utils-385e2d09.js';
7
+ import { s as slash } from './utils-576876dc.js';
8
8
  import fs, { realpathSync, statSync, Stats, promises } from 'fs';
9
9
  import assert from 'assert';
10
10
  import { format as format$3, inspect } from 'util';
11
11
  import { s as send } from './rpc-7de86f29.js';
12
12
  import 'tty';
13
+ import 'local-pkg';
13
14
 
14
15
  function normalizeWindowsPath$2(input = "") {
15
16
  if (!input.includes("\\")) {
@@ -8370,15 +8371,7 @@ ${[...callstack, dep].reverse().map((p) => `- ${p}`).join("\n")}`);
8370
8371
  }
8371
8372
  }
8372
8373
  function normalizeId(id) {
8373
- if (id && id.startsWith("/@id/__x00__"))
8374
- id = `\0${id.slice("/@id/__x00__".length)}`;
8375
- if (id && id.startsWith("/@id/"))
8376
- id = id.slice("/@id/".length);
8377
- if (id.startsWith("__vite-browser-external:"))
8378
- id = id.slice("__vite-browser-external:".length);
8379
- if (id.startsWith("node:"))
8380
- id = id.slice("node:".length);
8381
- return id;
8374
+ return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^node:/, "").replace(/[?&]v=\w+/, "?").replace(/\?$/, "");
8382
8375
  }
8383
8376
  async function shouldExternalize(id, config) {
8384
8377
  if (matchExternalizePattern(id, config.inline))
@@ -8392,11 +8385,10 @@ async function shouldExternalize(id, config) {
8392
8385
  return id.includes("/node_modules/") && await isValidNodeImport(id);
8393
8386
  }
8394
8387
  function toFilePath(id, root) {
8395
- id = slash(id);
8396
- let absolute = id.startsWith("/@fs/") ? id.slice(4) : id.startsWith(dirname$3(root)) ? id : id.startsWith("/") ? slash(resolve$3(root, id.slice(1))) : id;
8388
+ let absolute = slash(id).startsWith("/@fs/") ? id.slice(4) : id.startsWith(dirname$3(root)) ? id : id.startsWith("/") ? slash(resolve$3(root, id.slice(1))) : id;
8397
8389
  if (absolute.startsWith("//"))
8398
8390
  absolute = absolute.slice(1);
8399
- return isWindows && absolute.startsWith("/") ? pathToFileURL(absolute.slice(1)).href : absolute;
8391
+ return isWindows && absolute.startsWith("/") ? fileURLToPath(pathToFileURL(absolute.slice(1)).href) : absolute;
8400
8392
  }
8401
8393
  function matchExternalizePattern(id, patterns) {
8402
8394
  for (const ex of patterns) {
@@ -8411,8 +8403,8 @@ function matchExternalizePattern(id, patterns) {
8411
8403
  return false;
8412
8404
  }
8413
8405
  function patchWindowsImportPath(path) {
8414
- if (path.match(/^\w:\//))
8415
- return `/${path}`;
8406
+ if (path.match(/^\w:\\/))
8407
+ return `file:///${slash(path)}`;
8416
8408
  else
8417
8409
  return path;
8418
8410
  }
package/global.d.ts CHANGED
@@ -5,9 +5,8 @@ declare global {
5
5
  const it: typeof import('vitest')['it']
6
6
  const expect: typeof import('vitest')['expect']
7
7
  const assert: typeof import('vitest')['assert']
8
- const spy: typeof import('vitest')['spy']
9
- const spyOn: typeof import('vitest')['spyOn']
10
8
  const vitest: typeof import('vitest')['vitest']
9
+ const vi: typeof import('vitest')['vitest']
11
10
  const beforeAll: typeof import('vitest')['beforeAll']
12
11
  const afterAll: typeof import('vitest')['afterAll']
13
12
  const beforeEach: typeof import('vitest')['beforeEach']
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitest",
3
- "version": "0.0.89",
3
+ "version": "0.0.93",
4
4
  "description": "A blazing fast unit test framework powered by Vite",
5
5
  "keywords": [
6
6
  "vite",
@@ -51,27 +51,29 @@
51
51
  "chai": "^4.3.4",
52
52
  "chai-subset": "^1.6.0",
53
53
  "fast-glob": "^3.2.7",
54
- "flatted": "^3.2.4",
55
54
  "local-pkg": "^0.4.0",
56
- "micromatch": "^4.0.4",
57
55
  "piscina": "^3.2.0",
58
56
  "source-map": "^0.7.3",
59
57
  "tinyspy": "^0.1.0"
60
58
  },
61
59
  "devDependencies": {
60
+ "@antfu/install-pkg": "^0.1.0",
62
61
  "@types/diff": "^5.0.1",
63
62
  "@types/jsdom": "^16.2.13",
64
63
  "@types/micromatch": "^4.0.2",
65
64
  "@types/natural-compare": "^1.4.1",
66
- "@types/node": "^16.11.13",
65
+ "@types/node": "^17.0.0",
66
+ "@types/prompts": "^2.0.14",
67
67
  "c8": "^7.10.0",
68
68
  "cac": "^6.7.12",
69
69
  "cli-truncate": "^3.1.0",
70
70
  "diff": "^5.0.0",
71
71
  "find-up": "^6.2.0",
72
+ "flatted": "^3.2.4",
72
73
  "happy-dom": "^2.24.5",
73
74
  "jsdom": "^19.0.0",
74
75
  "log-update": "^5.0.0",
76
+ "micromatch": "^4.0.4",
75
77
  "mlly": "^0.3.15",
76
78
  "nanoid": "^3.1.30",
77
79
  "natural-compare": "^1.4.0",
@@ -79,8 +81,10 @@
79
81
  "picocolors": "^1.0.0",
80
82
  "pkg-types": "^0.3.2",
81
83
  "pretty-format": "^27.4.2",
84
+ "prompts": "^2.4.2",
82
85
  "rollup": "^2.61.1",
83
- "strip-ansi": "^7.0.1"
86
+ "strip-ansi": "^7.0.1",
87
+ "typescript": "^4.5.4"
84
88
  },
85
89
  "peerDependencies": {
86
90
  "c8": "*",
@@ -106,5 +110,6 @@
106
110
  "build": "rimraf dist && rollup -c",
107
111
  "dev": "rollup -c --watch src",
108
112
  "typecheck": "tsc --noEmit"
109
- }
113
+ },
114
+ "readme": "# vitest\n\n[![NPM version](https://img.shields.io/npm/v/vitest?color=a1b858&label=)](https://www.npmjs.com/package/vitest)\n\nA blazing fast unit test framework powered by Vite.\n\n> **This project is currently in closed beta exclusively for Sponsors.**<br>\n> Become a Sponsor of [@patak-dev](https://github.com/sponsors/patak-dev) or [@antfu](https://github.com/sponsors/antfu) to access the source code and issues tracker.\n> Learn more at [vitest.dev](https://vitest.dev)\n"
110
115
  }
@@ -1,122 +0,0 @@
1
- import { g as getCurrentSuite, w as withTimeout, a as getDefaultHookTimeout, s as suite, t as test, d as describe, i as it } from './suite-b8c6cb53.js';
2
- import chai, { util, assert, should, expect } from 'chai';
3
- import * as tinyspy from 'tinyspy';
4
- import { spy, spyOn as spyOn$1 } from 'tinyspy';
5
-
6
- const beforeAll = (fn, timeout) => getCurrentSuite().on("beforeAll", withTimeout(fn, timeout ?? getDefaultHookTimeout()));
7
- const afterAll = (fn, timeout) => getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout()));
8
- const beforeEach = (fn, timeout) => getCurrentSuite().on("beforeEach", withTimeout(fn, timeout ?? getDefaultHookTimeout()));
9
- const afterEach = (fn, timeout) => getCurrentSuite().on("afterEach", withTimeout(fn, timeout ?? getDefaultHookTimeout()));
10
-
11
- function spyOn(obj, method, accessType) {
12
- const dictionary = {
13
- get: "getter",
14
- set: "setter"
15
- };
16
- const objMethod = accessType ? { [dictionary[accessType]]: method } : method;
17
- const stub = tinyspy.spyOn(obj, objMethod);
18
- return enhanceSpy(stub);
19
- }
20
- function enhanceSpy(spy) {
21
- const stub = spy;
22
- let implementation;
23
- const instances = [];
24
- const mockContext = {
25
- get calls() {
26
- return stub.calls;
27
- },
28
- get instances() {
29
- return instances;
30
- },
31
- get invocationCallOrder() {
32
- return [];
33
- },
34
- get results() {
35
- return stub.results.map(([callType, value]) => {
36
- const type = callType === "error" ? "throw" : "return";
37
- return { type, value };
38
- });
39
- }
40
- };
41
- let onceImplementations = [];
42
- let name = "";
43
- Object.defineProperty(stub, "name", {
44
- get: () => name
45
- });
46
- stub.getMockName = () => name || "vi.fn()";
47
- stub.mockName = (n) => {
48
- name = n;
49
- return stub;
50
- };
51
- stub.mockClear = () => {
52
- stub.reset();
53
- return stub;
54
- };
55
- stub.mockReset = () => {
56
- stub.reset();
57
- return stub;
58
- };
59
- stub.mockRestore = () => {
60
- implementation = void 0;
61
- onceImplementations = [];
62
- stub.reset();
63
- stub.restore();
64
- return stub;
65
- };
66
- stub.getMockImplementation = () => implementation;
67
- stub.mockImplementation = (fn2) => {
68
- implementation = fn2;
69
- return stub;
70
- };
71
- stub.mockImplementationOnce = (fn2) => {
72
- onceImplementations.push(fn2);
73
- return stub;
74
- };
75
- stub.mockReturnThis = () => stub.mockImplementation(function() {
76
- return this;
77
- });
78
- stub.mockReturnValue = (val) => stub.mockImplementation(() => val);
79
- stub.mockReturnValueOnce = (val) => stub.mockImplementationOnce(() => val);
80
- stub.mockResolvedValue = (val) => stub.mockImplementation(() => Promise.resolve(val));
81
- stub.mockResolvedValueOnce = (val) => stub.mockImplementationOnce(() => Promise.resolve(val));
82
- stub.mockRejectedValue = (val) => stub.mockImplementation(() => Promise.reject(val));
83
- stub.mockRejectedValueOnce = (val) => stub.mockImplementation(() => Promise.reject(val));
84
- util.addProperty(stub, "mock", () => mockContext);
85
- stub.willCall(function(...args) {
86
- instances.push(this);
87
- const impl = onceImplementations.shift() || implementation || stub.getOriginal() || (() => {
88
- });
89
- return impl.apply(this, args);
90
- });
91
- return stub;
92
- }
93
- function fn(implementation) {
94
- return enhanceSpy(tinyspy.spyOn({ fn: implementation || (() => {
95
- }) }, "fn"));
96
- }
97
-
98
- const vitest = {
99
- spyOn,
100
- fn
101
- };
102
-
103
- var index = /*#__PURE__*/Object.freeze({
104
- __proto__: null,
105
- suite: suite,
106
- test: test,
107
- describe: describe,
108
- it: it,
109
- beforeAll: beforeAll,
110
- afterAll: afterAll,
111
- beforeEach: beforeEach,
112
- afterEach: afterEach,
113
- assert: assert,
114
- should: should,
115
- expect: expect,
116
- chai: chai,
117
- spy: spy,
118
- spyOn: spyOn$1,
119
- vitest: vitest
120
- });
121
-
122
- export { afterAll as a, beforeAll as b, beforeEach as c, afterEach as d, index as i, vitest as v };