vitest 0.0.107 → 0.0.111

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/worker.js CHANGED
@@ -1,11 +1,11 @@
1
- import { d as slash, m as resolve, j as dirname$2, a as spyOn, u as mergeSlashes, s as spies, k as basename$2 } from './utils-92ec89d1.js';
2
- import { n as nanoid } from './index-9e71c815.js';
3
- import { c as distDir } from './constants-82dad049.js';
1
+ import { h as resolve, d as dirname$2, b as basename$2, m as mergeSlashes, s as slash } from './utils-cb6b1266.js';
2
+ import { a as spyOn, s as spies, n as nanoid } from './jest-mock-a57b745c.js';
3
+ import { c as distDir } from './constants-2b0310b7.js';
4
4
  import { builtinModules, createRequire } from 'module';
5
5
  import { pathToFileURL, fileURLToPath as fileURLToPath$2, URL as URL$1 } from 'url';
6
- import fs, { promises, realpathSync, statSync, Stats, readdirSync, existsSync } from 'fs';
7
6
  import vm from 'vm';
8
7
  import path from 'path';
8
+ import fs, { promises, realpathSync, statSync, Stats, readdirSync, existsSync } from 'fs';
9
9
  import assert from 'assert';
10
10
  import { format as format$2, inspect } from 'util';
11
11
  import { s as send } from './rpc-7de86f29.js';
@@ -9215,6 +9215,105 @@ var __spreadValues = (a, b) => {
9215
9215
  }
9216
9216
  return a;
9217
9217
  };
9218
+ function resolveMockPath(mockPath, root, nmName) {
9219
+ if (nmName) {
9220
+ const mockFolder = resolve(root, "__mocks__");
9221
+ const files = readdirSync(mockFolder);
9222
+ for (const file of files) {
9223
+ const [basename2] = file.split(".");
9224
+ if (basename2 === nmName)
9225
+ return resolve(mockFolder, file).replace(root, "");
9226
+ }
9227
+ return null;
9228
+ }
9229
+ const dir = dirname$2(mockPath);
9230
+ const baseId = basename$2(mockPath);
9231
+ const fullPath = resolve(dir, "__mocks__", baseId);
9232
+ return existsSync(fullPath) ? fullPath.replace(root, "") : null;
9233
+ }
9234
+ function getObjectType(value) {
9235
+ return Object.prototype.toString.apply(value).slice(8, -1);
9236
+ }
9237
+ function mockPrototype(proto) {
9238
+ if (!proto)
9239
+ return null;
9240
+ const newProto = {};
9241
+ const protoDescr = Object.getOwnPropertyDescriptors(proto);
9242
+ for (const d in protoDescr) {
9243
+ Object.defineProperty(newProto, d, protoDescr[d]);
9244
+ if (typeof protoDescr[d].value === "function")
9245
+ spyOn(newProto, d).mockImplementation(() => {
9246
+ });
9247
+ }
9248
+ return newProto;
9249
+ }
9250
+ function mockObject(obj) {
9251
+ const type = getObjectType(obj);
9252
+ if (Array.isArray(obj))
9253
+ return [];
9254
+ else if (type !== "Object" && type !== "Module")
9255
+ return obj;
9256
+ const newObj = __spreadValues({}, obj);
9257
+ const proto = mockPrototype(Object.getPrototypeOf(obj));
9258
+ Object.setPrototypeOf(newObj, proto);
9259
+ for (const k in obj) {
9260
+ newObj[k] = mockObject(obj[k]);
9261
+ const type2 = getObjectType(obj[k]);
9262
+ if (type2.includes("Function") && !obj[k].__isSpy) {
9263
+ spyOn(newObj, k).mockImplementation(() => {
9264
+ });
9265
+ Object.defineProperty(newObj[k], "length", { value: 0 });
9266
+ }
9267
+ }
9268
+ return newObj;
9269
+ }
9270
+ function createMocker(root, mockMap) {
9271
+ function getSuiteFilepath() {
9272
+ var _a;
9273
+ return (_a = process.__vitest_worker__) == null ? void 0 : _a.filepath;
9274
+ }
9275
+ function getActualPath(path, nmName) {
9276
+ return nmName ? mergeSlashes(`/@fs/${path}`) : path.replace(root, "");
9277
+ }
9278
+ function unmockPath(path, nmName) {
9279
+ const suitefile = getSuiteFilepath();
9280
+ if (suitefile) {
9281
+ const fsPath = getActualPath(path, nmName);
9282
+ mockMap[suitefile] ?? (mockMap[suitefile] = {});
9283
+ delete mockMap[suitefile][fsPath];
9284
+ }
9285
+ }
9286
+ function mockPath(path, nmName, factory) {
9287
+ const suitefile = getSuiteFilepath();
9288
+ if (suitefile) {
9289
+ const fsPath = getActualPath(path, nmName);
9290
+ mockMap[suitefile] ?? (mockMap[suitefile] = {});
9291
+ mockMap[suitefile][fsPath] = factory || resolveMockPath(path, root, nmName);
9292
+ }
9293
+ }
9294
+ function clearMocks({ clearMocks: clearMocks2, mockReset, restoreMocks }) {
9295
+ if (!clearMocks2 && !mockReset && !restoreMocks)
9296
+ return;
9297
+ spies.forEach((s) => {
9298
+ if (restoreMocks)
9299
+ s.mockRestore();
9300
+ else if (mockReset)
9301
+ s.mockReset();
9302
+ else if (clearMocks2)
9303
+ s.mockClear();
9304
+ });
9305
+ }
9306
+ return {
9307
+ mockPath,
9308
+ unmockPath,
9309
+ clearMocks,
9310
+ getActualPath,
9311
+ mockObject,
9312
+ getSuiteFilepath,
9313
+ resolveMockPath
9314
+ };
9315
+ }
9316
+
9218
9317
  const defaultInline = [
9219
9318
  "vitest/dist",
9220
9319
  /virtual:/,
@@ -9262,84 +9361,46 @@ async function interpretedImport(path, interpretDefault) {
9262
9361
  }
9263
9362
  return mod;
9264
9363
  }
9265
- function resolveMockPath(mockPath, root, nmName) {
9266
- if (nmName) {
9267
- const mockFolder = resolve(root, "__mocks__");
9268
- const files = readdirSync(mockFolder);
9269
- for (const file of files) {
9270
- const [basename2] = file.split(".");
9271
- if (basename2 === nmName)
9272
- return resolve(mockFolder, file).replace(root, "");
9273
- }
9274
- return null;
9275
- }
9276
- const dir = dirname$2(mockPath);
9277
- const baseId = basename$2(mockPath);
9278
- const fullPath = resolve(dir, "__mocks__", baseId);
9279
- return existsSync(fullPath) ? fullPath.replace(root, "") : null;
9280
- }
9281
- function mockObject(obj) {
9282
- const newObj = __spreadValues({}, obj);
9283
- for (const k in obj) {
9284
- newObj[k] = obj[k];
9285
- if (typeof obj[k] === "function" && !obj[k].__isSpy)
9286
- spyOn(newObj, k);
9287
- }
9288
- return newObj;
9289
- }
9290
9364
  async function executeInViteNode(options) {
9291
9365
  const { moduleCache, root, files, fetch, mockMap } = options;
9292
9366
  const externalCache = /* @__PURE__ */ new Map();
9293
9367
  builtinModules.forEach((m) => externalCache.set(m, true));
9368
+ const {
9369
+ getActualPath,
9370
+ getSuiteFilepath,
9371
+ mockObject,
9372
+ mockPath,
9373
+ clearMocks,
9374
+ unmockPath,
9375
+ resolveMockPath
9376
+ } = createMocker(root, mockMap);
9294
9377
  const result = [];
9295
9378
  for (const file of files)
9296
9379
  result.push(await cachedRequest(`/@fs/${slash(resolve(file))}`, []));
9297
9380
  return result;
9298
- function getSuiteFilepath() {
9381
+ async function callFunctionMock(dep, mock) {
9299
9382
  var _a;
9300
- return (_a = process.__vitest_worker__) == null ? void 0 : _a.filepath;
9301
- }
9302
- function getActualPath(path, nmName) {
9303
- return nmName ? mergeSlashes(`/@fs/${path}`) : path.replace(root, "");
9304
- }
9305
- function unmockPath(path, nmName) {
9306
- const suitefile = getSuiteFilepath();
9307
- if (suitefile) {
9308
- const fsPath = getActualPath(path, nmName);
9309
- mockMap[suitefile] ?? (mockMap[suitefile] = {});
9310
- delete mockMap[suitefile][fsPath];
9311
- }
9312
- }
9313
- function mockPath(path, nmName) {
9314
- const suitefile = getSuiteFilepath();
9315
- if (suitefile) {
9316
- const mockPath2 = resolveMockPath(path, root, nmName);
9317
- const fsPath = getActualPath(path, nmName);
9318
- mockMap[suitefile] ?? (mockMap[suitefile] = {});
9319
- mockMap[suitefile][fsPath] = mockPath2;
9320
- }
9321
- }
9322
- function clearMocks({ clearMocks: clearMocks2, mockReset, restoreMocks }) {
9323
- if (!clearMocks2 && !mockReset && !restoreMocks)
9324
- return;
9325
- spies.forEach((s) => {
9326
- if (restoreMocks)
9327
- s.mockRestore();
9328
- else if (mockReset)
9329
- s.mockReset();
9330
- else if (clearMocks2)
9331
- s.mockClear();
9332
- });
9383
+ const name = `${dep}__mock`;
9384
+ const cached = (_a = moduleCache.get(name)) == null ? void 0 : _a.exports;
9385
+ if (cached)
9386
+ return cached;
9387
+ const exports = await mock();
9388
+ setCache(name, { exports });
9389
+ return exports;
9333
9390
  }
9334
9391
  async function directRequest(id, fsPath, callstack) {
9335
9392
  callstack = [...callstack, id];
9336
9393
  const suite = getSuiteFilepath();
9337
9394
  const request = async (dep, canMock = true) => {
9338
9395
  var _a;
9339
- const mocks2 = mockMap[suite || ""] || {};
9340
- const mock = mocks2[dep];
9341
- if (mock && canMock)
9342
- dep = mock;
9396
+ if (canMock) {
9397
+ const mocks2 = mockMap[suite || ""] || {};
9398
+ const mock = mocks2[dep];
9399
+ if (typeof mock === "function")
9400
+ return callFunctionMock(dep, mock);
9401
+ if (typeof mock === "string")
9402
+ dep = mock;
9403
+ }
9343
9404
  if (callstack.includes(dep)) {
9344
9405
  const cacheKey = toFilePath(dep, root);
9345
9406
  if (!((_a = moduleCache.get(cacheKey)) == null ? void 0 : _a.exports))
@@ -9372,12 +9433,18 @@ ${[...callstack, dep].reverse().map((p) => `- ${p}`).join("\n")}`);
9372
9433
  return request(getActualPath(path, nmName), false);
9373
9434
  };
9374
9435
  const importMock = async (path, nmName) => {
9375
- const mockPath2 = resolveMockPath(path, root, nmName);
9376
- if (mockPath2 === null) {
9377
- const exports2 = await request(getActualPath(path, nmName), false);
9378
- return mockObject(exports2);
9436
+ if (!suite)
9437
+ throw new Error("You can import mock only inside of a running test");
9438
+ const mock = (mockMap[suite] || {})[path] || resolveMockPath(path, root, nmName);
9439
+ if (mock === null) {
9440
+ const fsPath2 = getActualPath(path, nmName);
9441
+ const exports2 = mockObject(await request(fsPath2, false));
9442
+ setCache(fsPath2, { exports: exports2 });
9443
+ return exports2;
9379
9444
  }
9380
- return request(mockPath2, true);
9445
+ if (typeof mock === "function")
9446
+ return callFunctionMock(path, mock);
9447
+ return request(mock, true);
9381
9448
  };
9382
9449
  const context = {
9383
9450
  __vite_ssr_import__: request,
@@ -9523,10 +9590,13 @@ async function startViteNode(ctx) {
9523
9590
  return _viteNode;
9524
9591
  }
9525
9592
  function init(ctx) {
9593
+ if (process.__vitest_worker__ && ctx.config.threads)
9594
+ throw new Error(`worker for ${ctx.files.join(",")} already initialized by ${process.__vitest_worker__.ctx.files.join(",")}. This is probably an internal bug of Vitest.`);
9526
9595
  process.stdout.write("\0");
9527
9596
  const { config, port } = ctx;
9528
9597
  const rpcPromiseMap = /* @__PURE__ */ new Map();
9529
9598
  process.__vitest_worker__ = {
9599
+ ctx,
9530
9600
  moduleCache,
9531
9601
  config,
9532
9602
  rpc: (method, ...args) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitest",
3
- "version": "0.0.107",
3
+ "version": "0.0.111",
4
4
  "description": "A blazing fast unit test framework powered by Vite",
5
5
  "keywords": [
6
6
  "vite",
@@ -51,16 +51,16 @@
51
51
  "@types/chai-subset": "^1.3.3",
52
52
  "chai": "^4.3.4",
53
53
  "local-pkg": "^0.4.0",
54
- "tinypool": "^0.0.5",
55
- "tinyspy": "^0.2.4"
54
+ "tinypool": "^0.0.6",
55
+ "tinyspy": "^0.2.6"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@antfu/install-pkg": "^0.1.0",
59
- "@types/diff": "^5.0.1",
59
+ "@types/diff": "^5.0.2",
60
60
  "@types/jsdom": "^16.2.14",
61
61
  "@types/micromatch": "^4.0.2",
62
62
  "@types/natural-compare": "^1.4.1",
63
- "@types/node": "^17.0.2",
63
+ "@types/node": "^17.0.4",
64
64
  "@types/prompts": "^2.4.0",
65
65
  "c8": "^7.10.0",
66
66
  "cac": "^6.7.12",
@@ -84,7 +84,7 @@
84
84
  "pkg-types": "^0.3.2",
85
85
  "pretty-format": "^27.4.2",
86
86
  "prompts": "^2.4.2",
87
- "rollup": "^2.61.1",
87
+ "rollup": "^2.62.0",
88
88
  "source-map-js": "^1.0.1",
89
89
  "strip-ansi": "^7.0.1",
90
90
  "typescript": "^4.5.4"
@@ -1,19 +0,0 @@
1
- import { g as globalApis } from './constants-82dad049.js';
2
- import { i as index } from './index-77f19d39.js';
3
- import 'url';
4
- import './utils-92ec89d1.js';
5
- import 'tty';
6
- import 'local-pkg';
7
- import 'path';
8
- import 'chai';
9
- import 'tinyspy';
10
- import './suite-ff89a82e.js';
11
- import './index-9e71c815.js';
12
-
13
- function registerApiGlobally() {
14
- globalApis.forEach((api) => {
15
- globalThis[api] = index[api];
16
- });
17
- }
18
-
19
- export { registerApiGlobally };
@@ -1,12 +0,0 @@
1
- let urlAlphabet =
2
- 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
3
- let nanoid = (size = 21) => {
4
- let id = '';
5
- let i = size;
6
- while (i--) {
7
- id += urlAlphabet[(Math.random() * 64) | 0];
8
- }
9
- return id
10
- };
11
-
12
- export { nanoid as n };
@@ -1,201 +0,0 @@
1
- import { n as nanoid } from './index-9e71c815.js';
2
- import { n as noop } from './utils-92ec89d1.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 };