vitest 0.25.8 → 0.26.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 (33) hide show
  1. package/LICENSE.md +0 -142
  2. package/dist/browser.d.ts +6 -3
  3. package/dist/browser.js +9 -10
  4. package/dist/{chunk-api-setup.dc71e384.js → chunk-api-setup.08f3b356.js} +39 -42
  5. package/dist/{chunk-integrations-globals.4d261bb8.js → chunk-integrations-globals.cab94a09.js} +5 -5
  6. package/dist/{chunk-runtime-chain.f86e5250.js → chunk-runtime-chain.e655f6cc.js} +4 -5
  7. package/dist/{chunk-runtime-error.616e92ca.js → chunk-runtime-error.dfbbf9be.js} +5 -5
  8. package/dist/{chunk-runtime-mocker.99b910d0.js → chunk-runtime-mocker.35fabb8b.js} +65 -64
  9. package/dist/{chunk-runtime-rpc.42aebbb9.js → chunk-runtime-rpc.7959fc79.js} +1 -1
  10. package/dist/{chunk-runtime-setup.5398e2c4.js → chunk-runtime-setup.4c1b529e.js} +16 -29
  11. package/dist/{chunk-vite-node-externalize.b9495318.js → chunk-snapshot-manager.7d978f79.js} +36 -322
  12. package/dist/{chunk-typecheck-constants.ed987901.js → chunk-typecheck-constants.3f865d14.js} +5 -4
  13. package/dist/{chunk-runtime-test-state.3f86f48f.js → chunk-utils-import.ca62c9d7.js} +49 -18
  14. package/dist/{chunk-utils-source-map.29ff1088.js → chunk-utils-source-map.5bbb50cd.js} +6 -4
  15. package/dist/cli.js +12 -13
  16. package/dist/config.d.ts +4 -1
  17. package/dist/entry.js +9 -9
  18. package/dist/environments.d.ts +4 -1
  19. package/dist/{index-5aad25c1.d.ts → index-c3f83a58.d.ts} +1 -1
  20. package/dist/index.d.ts +28 -10
  21. package/dist/index.js +6 -6
  22. package/dist/loader.js +7 -6
  23. package/dist/node.d.ts +18 -18
  24. package/dist/node.js +14 -14
  25. package/dist/suite.js +4 -4
  26. package/dist/{types-71ccd11d.d.ts → types-56bcd6c3.d.ts} +16 -273
  27. package/dist/vendor-index.783e7f3e.js +71 -0
  28. package/dist/vendor-index.96e022fd.js +211 -0
  29. package/dist/worker.js +12 -14
  30. package/package.json +4 -4
  31. package/dist/chunk-vite-node-source-map.b4ea5792.js +0 -446
  32. package/dist/chunk-vite-node-utils.0e4a6a88.js +0 -1385
  33. package/dist/vendor-source-map-support.1ce17397.js +0 -707
@@ -1,9 +1,9 @@
1
- import { V as ViteNodeRunner } from './chunk-vite-node-source-map.b4ea5792.js';
1
+ import { ViteNodeRunner } from 'vite-node/client';
2
2
  import { normalizePath } from 'vite';
3
- import { g as getWorkerState, J as mergeSlashes, s as slash, x as getType, K as getAllMockableProperties } from './chunk-typecheck-constants.ed987901.js';
3
+ import { g as getWorkerState, y as getType, K as getAllMockableProperties, e as getCurrentEnvironment } from './chunk-typecheck-constants.3f865d14.js';
4
4
  import { existsSync, readdirSync } from 'fs';
5
- import { c as normalizeRequestId, p as pathFromRoot, i as isNodeBuiltin } from './chunk-vite-node-utils.0e4a6a88.js';
6
- import { p as picocolors, d as dirname, j as join, c as basename, l as extname, b as resolve, e as distDir } from './chunk-utils-env.03f840f2.js';
5
+ import { i as isNodeBuiltin } from './vendor-index.96e022fd.js';
6
+ import { b as resolve, e as distDir, g as isAbsolute, p as picocolors, d as dirname, j as join, c as basename, l as extname } from './chunk-utils-env.03f840f2.js';
7
7
 
8
8
  class RefTracker {
9
9
  constructor() {
@@ -27,20 +27,21 @@ function isSpecialProp(prop, parentType) {
27
27
  return parentType.includes("Function") && typeof prop === "string" && ["arguments", "callee", "caller", "length", "name"].includes(prop);
28
28
  }
29
29
  const _VitestMocker = class {
30
- constructor(options, moduleCache, request) {
31
- this.options = options;
32
- this.moduleCache = moduleCache;
33
- this.request = request;
30
+ constructor(runner) {
31
+ this.runner = runner;
34
32
  this.resolveCache = /* @__PURE__ */ new Map();
35
33
  }
36
34
  get root() {
37
- return this.options.root;
35
+ return this.runner.options.root;
38
36
  }
39
37
  get base() {
40
- return this.options.base;
38
+ return this.runner.options.base;
41
39
  }
42
40
  get mockMap() {
43
- return this.options.mockMap;
41
+ return this.runner.options.mockMap;
42
+ }
43
+ get moduleCache() {
44
+ return this.runner.moduleCache;
44
45
  }
45
46
  getSuiteFilepath() {
46
47
  return getWorkerState().filepath || "global";
@@ -54,21 +55,22 @@ const _VitestMocker = class {
54
55
  ...suiteMocks
55
56
  };
56
57
  }
57
- async resolvePath(id, importer) {
58
- const path = await this.options.resolveId(id, importer);
59
- const external = path == null || path.id.includes("/node_modules/") ? id : null;
58
+ async resolvePath(rawId, importer) {
59
+ const [id, fsPath] = await this.runner.resolveUrl(rawId, importer);
60
+ const external = !isAbsolute(fsPath) || fsPath.includes("/node_modules/") ? rawId : null;
60
61
  return {
61
- path: normalizeRequestId((path == null ? void 0 : path.id) || id),
62
+ id,
63
+ fsPath,
62
64
  external
63
65
  };
64
66
  }
65
67
  async resolveMocks() {
66
68
  await Promise.all(_VitestMocker.pendingIds.map(async (mock) => {
67
- const { path, external } = await this.resolvePath(mock.id, mock.importer);
69
+ const { fsPath, external } = await this.resolvePath(mock.id, mock.importer);
68
70
  if (mock.type === "unmock")
69
- this.unmockPath(path);
71
+ this.unmockPath(fsPath);
70
72
  if (mock.type === "mock")
71
- this.mockPath(mock.id, path, external, mock.factory);
73
+ this.mockPath(mock.id, fsPath, external, mock.factory);
72
74
  }));
73
75
  _VitestMocker.pendingIds = [];
74
76
  }
@@ -82,15 +84,15 @@ const _VitestMocker = class {
82
84
  exports = await mock();
83
85
  } catch (err) {
84
86
  const vitestError = new Error(
85
- "[vitest] There was an error, when mocking a module. If you are using vi.mock, make sure you are not using top level variables inside, since this call is hoisted. Read more: https://vitest.dev/api/#vi-mock"
87
+ '[vitest] There was an error, when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/#vi-mock'
86
88
  );
87
89
  vitestError.cause = err;
88
90
  throw vitestError;
89
91
  }
90
- if (exports === null || typeof exports !== "object")
91
- throw new Error('[vitest] vi.mock(path: string, factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?');
92
- const filepath = dep.slice("mock:".length);
92
+ const filepath = dep.slice(5);
93
93
  const mockpath = ((_b = this.resolveCache.get(this.getSuiteFilepath())) == null ? void 0 : _b[filepath]) || filepath;
94
+ if (exports === null || typeof exports !== "object")
95
+ throw new Error(`[vitest] vi.mock("${mockpath}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
94
96
  const moduleExports = new Proxy(exports, {
95
97
  get(target, prop) {
96
98
  const val = target[prop];
@@ -106,7 +108,7 @@ ${picocolors.exports.green(`vi.mock("${mockpath}", async () => {
106
108
  const actual = await vi.importActual("${mockpath}")
107
109
  return {
108
110
  ...actual,
109
- // your mock
111
+ // your mocked methods
110
112
  },
111
113
  })`)}
112
114
  `
@@ -125,15 +127,10 @@ ${picocolors.exports.green(`vi.mock("${mockpath}", async () => {
125
127
  return this.getMocks()[id];
126
128
  }
127
129
  normalizePath(path) {
128
- return pathFromRoot(this.root, normalizeRequestId(path, this.base));
129
- }
130
- getFsPath(path, external) {
131
- if (external)
132
- return mergeSlashes(`/@fs/${path}`);
133
- return normalizeRequestId(path, this.base);
130
+ return this.moduleCache.normalizePath(path);
134
131
  }
135
132
  resolveMockPath(mockPath, external) {
136
- const path = normalizeRequestId(external || mockPath);
133
+ const path = external || mockPath;
137
134
  if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
138
135
  const mockDirname = dirname(path);
139
136
  const mockFolder = join(this.root, "__mocks__", mockDirname);
@@ -235,41 +232,35 @@ ${picocolors.exports.green(`vi.mock("${mockpath}", async () => {
235
232
  this.mockMap.set(suitefile, mocks);
236
233
  this.resolveCache.set(suitefile, resolves);
237
234
  }
238
- async importActual(id, importer) {
239
- const { path, external } = await this.resolvePath(id, importer);
240
- const fsPath = this.getFsPath(path, external);
241
- const result = await this.request(fsPath);
235
+ async importActual(rawId, importee) {
236
+ const { id, fsPath } = await this.resolvePath(rawId, importee);
237
+ const result = await this.runner.cachedRequest(id, fsPath, [importee]);
242
238
  return result;
243
239
  }
244
- async importMock(id, importer) {
245
- const { path, external } = await this.resolvePath(id, importer);
246
- const fsPath = this.getFsPath(path, external);
240
+ async importMock(rawId, importee) {
241
+ const { id, fsPath, external } = await this.resolvePath(rawId, importee);
247
242
  const normalizedId = this.normalizePath(fsPath);
248
243
  let mock = this.getDependencyMock(normalizedId);
249
244
  if (mock === void 0)
250
245
  mock = this.resolveMockPath(fsPath, external);
251
246
  if (mock === null) {
252
- await this.ensureSpy();
253
- const mod = await this.request(fsPath);
247
+ const mod = await this.runner.cachedRequest(id, fsPath, [importee]);
254
248
  return this.mockObject(mod);
255
249
  }
256
250
  if (typeof mock === "function")
257
251
  return this.callFunctionMock(fsPath, mock);
258
- return this.requestWithMock(mock);
252
+ return this.runner.dependencyRequest(mock, mock, [importee]);
259
253
  }
260
- async ensureSpy() {
254
+ async initializeSpyModule() {
261
255
  if (_VitestMocker.spyModule)
262
256
  return;
263
- _VitestMocker.spyModule = await this.request(`/@fs/${slash(resolve(distDir, "spy.js"))}`);
264
- }
265
- async requestWithMock(dep) {
266
- await Promise.all([
267
- this.ensureSpy(),
268
- this.resolveMocks()
269
- ]);
270
- const id = this.normalizePath(dep);
257
+ _VitestMocker.spyModule = await this.runner.executeId(_VitestMocker.spyModulePath);
258
+ }
259
+ async requestWithMock(url, callstack) {
260
+ if (_VitestMocker.pendingIds.length)
261
+ await this.resolveMocks();
262
+ const id = this.normalizePath(url);
271
263
  const mock = this.getDependencyMock(id);
272
- const callstack = this.request.callstack;
273
264
  const mockPath = this.getMockPath(id);
274
265
  if (mock === null) {
275
266
  const cache = this.moduleCache.get(mockPath);
@@ -277,11 +268,11 @@ ${picocolors.exports.green(`vi.mock("${mockpath}", async () => {
277
268
  return cache.exports;
278
269
  const exports = {};
279
270
  this.moduleCache.set(mockPath, { exports });
280
- const mod = await this.request(dep);
271
+ const mod = await this.runner.directRequest(url, url, []);
281
272
  this.mockObject(mod, exports);
282
273
  return exports;
283
274
  }
284
- if (typeof mock === "function" && !callstack.includes(mockPath)) {
275
+ if (typeof mock === "function" && !callstack.includes(mockPath) && !callstack.includes(url)) {
285
276
  callstack.push(mockPath);
286
277
  const result = await this.callFunctionMock(mockPath, mock);
287
278
  const indexMock = callstack.indexOf(mockPath);
@@ -289,8 +280,8 @@ ${picocolors.exports.green(`vi.mock("${mockpath}", async () => {
289
280
  return result;
290
281
  }
291
282
  if (typeof mock === "string" && !callstack.includes(mock))
292
- dep = mock;
293
- return this.request(dep);
283
+ url = mock;
284
+ return url;
294
285
  }
295
286
  queueMock(id, importer, factory) {
296
287
  _VitestMocker.pendingIds.push({ type: "mock", id, importer, factory });
@@ -301,10 +292,12 @@ ${picocolors.exports.green(`vi.mock("${mockpath}", async () => {
301
292
  };
302
293
  let VitestMocker = _VitestMocker;
303
294
  VitestMocker.pendingIds = [];
295
+ VitestMocker.spyModulePath = resolve(distDir, "spy.js");
304
296
 
305
297
  async function executeInViteNode(options) {
306
298
  const runner = new VitestRunner(options);
307
299
  await runner.executeId("/@vite/env");
300
+ await runner.mocker.initializeSpyModule();
308
301
  const result = [];
309
302
  for (const file of options.files)
310
303
  result.push(await runner.executeFile(file));
@@ -314,25 +307,33 @@ class VitestRunner extends ViteNodeRunner {
314
307
  constructor(options) {
315
308
  super(options);
316
309
  this.options = options;
310
+ this.mocker = new VitestMocker(this);
311
+ }
312
+ async resolveUrl(id, importee) {
313
+ if (importee && importee.startsWith("mock:"))
314
+ importee = importee.slice(5);
315
+ return super.resolveUrl(id, importee);
316
+ }
317
+ async dependencyRequest(id, fsPath, callstack) {
318
+ const mocked = await this.mocker.requestWithMock(fsPath, callstack);
319
+ if (typeof mocked === "string")
320
+ return super.dependencyRequest(mocked, mocked, callstack);
321
+ if (mocked && typeof mocked === "object")
322
+ return mocked;
323
+ return super.dependencyRequest(id, fsPath, callstack);
317
324
  }
318
325
  prepareContext(context) {
319
- const request = context.__vite_ssr_import__;
320
- const resolveId = context.__vitest_resolve_id__;
321
- const resolveUrl = async (dep) => {
322
- const [id, resolvedId] = await resolveId(dep);
323
- return resolvedId || id;
324
- };
325
- const mocker = new VitestMocker(this.options, this.moduleCache, request);
326
326
  const workerState = getWorkerState();
327
327
  if (workerState.filepath && normalizePath(workerState.filepath) === normalizePath(context.__filename)) {
328
328
  Object.defineProperty(context.__vite_ssr_import_meta__, "vitest", { get: () => globalThis.__vitest_index__ });
329
329
  }
330
330
  return Object.assign(context, {
331
- __vite_ssr_import__: async (dep) => mocker.requestWithMock(await resolveUrl(dep)),
332
- __vite_ssr_dynamic_import__: async (dep) => mocker.requestWithMock(await resolveUrl(dep)),
333
- __vitest_mocker__: mocker
331
+ __vitest_mocker__: this.mocker
334
332
  });
335
333
  }
334
+ shouldInterop(path, mod) {
335
+ return this.options.interopDefault ?? (getCurrentEnvironment() !== "node" && super.shouldInterop(path, mod));
336
+ }
336
337
  }
337
338
 
338
339
  export { VitestRunner as V, executeInViteNode as e };
@@ -1,4 +1,4 @@
1
- import { g as getWorkerState } from './chunk-typecheck-constants.ed987901.js';
1
+ import { g as getWorkerState } from './chunk-typecheck-constants.3f865d14.js';
2
2
  import { s as safeSetTimeout } from './chunk-utils-timers.793fd179.js';
3
3
 
4
4
  const safeRandom = Math.random;
@@ -1,32 +1,15 @@
1
1
  import { performance } from 'perf_hooks';
2
2
  import { s as someTasksAreOnly, i as interpretTaskModes, t as takeCoverageInsideWorker, p as pLimit } from './chunk-integrations-coverage.befed097.js';
3
- import { r as resetRunOnceCounter, i as index, v as vi, s as setCurrentTest } from './chunk-runtime-test-state.3f86f48f.js';
4
- import { g as getWorkerState, R as RealDate, t as toArray, k as relativePath, h as isRunningInBenchmark, p as partitionSuiteChildren, l as shuffle, q as hasTests, u as hasFailed, v as createDefer, e as getFullName } from './chunk-typecheck-constants.ed987901.js';
5
- import { f as clearCollectorContext, h as defaultSuite, j as setHooks, k as getHooks, l as collectorContext, m as getBenchOptions, n as getFn, o as setState, G as GLOBAL_EXPECT, p as getState } from './chunk-runtime-chain.f86e5250.js';
6
- import { r as rpc } from './chunk-runtime-rpc.42aebbb9.js';
7
- import { p as processError } from './chunk-runtime-error.616e92ca.js';
8
- import { s as sourceMapSupport } from './vendor-source-map-support.1ce17397.js';
3
+ import { r as resetRunOnceCounter, i as index, v as vi, s as setCurrentTest } from './chunk-utils-import.ca62c9d7.js';
4
+ import { g as getWorkerState, R as RealDate, t as toArray, l as relativePath, j as isRunningInBenchmark, p as partitionSuiteChildren, q as shuffle, u as hasTests, v as hasFailed, w as createDefer, f as getFullName } from './chunk-typecheck-constants.3f865d14.js';
5
+ import { f as clearCollectorContext, h as defaultSuite, j as setHooks, k as getHooks, l as collectorContext, m as getBenchOptions, n as getFn, o as setState, G as GLOBAL_EXPECT, p as getState } from './chunk-runtime-chain.e655f6cc.js';
6
+ import { r as rpc } from './chunk-runtime-rpc.7959fc79.js';
7
+ import { p as processError } from './chunk-runtime-error.dfbbf9be.js';
8
+ import { installSourcemapsSupport } from 'vite-node/source-map';
9
9
  import { e as environments } from './chunk-env-node.67948209.js';
10
10
  import { i as isNode, a as isBrowser } from './chunk-utils-env.03f840f2.js';
11
11
  import { b as safeClearTimeout, s as safeSetTimeout } from './chunk-utils-timers.793fd179.js';
12
12
 
13
- function installSourcemapsSupport(options) {
14
- sourceMapSupport.exports.install({
15
- environment: "node",
16
- handleUncaughtExceptions: false,
17
- retrieveSourceMap(source) {
18
- const map = options.getSourceMap(source);
19
- if (map) {
20
- return {
21
- url: source,
22
- map
23
- };
24
- }
25
- return null;
26
- }
27
- });
28
- }
29
-
30
13
  let globalSetup = false;
31
14
  async function setupGlobalEnv(config) {
32
15
  resetRunOnceCounter();
@@ -46,7 +29,7 @@ async function setupGlobalEnv(config) {
46
29
  await setupConsoleLogSpy();
47
30
  }
48
31
  if (config.globals)
49
- (await import('./chunk-integrations-globals.4d261bb8.js')).registerApiGlobally();
32
+ (await import('./chunk-integrations-globals.cab94a09.js')).registerApiGlobally();
50
33
  }
51
34
  function setupDefines(defines) {
52
35
  for (const key in defines)
@@ -346,7 +329,7 @@ const callCleanupHooks = async (cleanups) => {
346
329
  async function runTest(test) {
347
330
  var _a, _b, _c;
348
331
  if (test.mode !== "run") {
349
- const { getSnapshotClient } = await import('./chunk-runtime-chain.f86e5250.js').then(function (n) { return n.r; });
332
+ const { getSnapshotClient } = await import('./chunk-runtime-chain.e655f6cc.js').then(function (n) { return n.r; });
350
333
  getSnapshotClient().skipTestSnapshots(test);
351
334
  return;
352
335
  }
@@ -363,7 +346,7 @@ async function runTest(test) {
363
346
  clearModuleMocks();
364
347
  setCurrentTest(test);
365
348
  if (isNode) {
366
- const { getSnapshotClient } = await import('./chunk-runtime-chain.f86e5250.js').then(function (n) { return n.r; });
349
+ const { getSnapshotClient } = await import('./chunk-runtime-chain.e655f6cc.js').then(function (n) { return n.r; });
367
350
  await getSnapshotClient().setTest(test);
368
351
  }
369
352
  const workerState = getWorkerState();
@@ -426,7 +409,7 @@ async function runTest(test) {
426
409
  console.error(test.result.error.message, test.result.error.stackStr);
427
410
  setCurrentTest(void 0);
428
411
  if (isNode) {
429
- const { getSnapshotClient } = await import('./chunk-runtime-chain.f86e5250.js').then(function (n) { return n.r; });
412
+ const { getSnapshotClient } = await import('./chunk-runtime-chain.e655f6cc.js').then(function (n) { return n.r; });
430
413
  getSnapshotClient().clearTest();
431
414
  }
432
415
  test.result.duration = now() - start;
@@ -632,7 +615,7 @@ async function startTestsBrowser(paths, config) {
632
615
  async function startTestsNode(paths, config) {
633
616
  const files = await collectTests(paths, config);
634
617
  rpc().onCollected(files);
635
- const { getSnapshotClient } = await import('./chunk-runtime-chain.f86e5250.js').then(function (n) { return n.r; });
618
+ const { getSnapshotClient } = await import('./chunk-runtime-chain.e655f6cc.js').then(function (n) { return n.r; });
636
619
  getSnapshotClient().clear();
637
620
  await runFiles(files, config);
638
621
  const coverage = await takeCoverageInsideWorker(config.coverage);
@@ -647,13 +630,17 @@ async function startTests(paths, config) {
647
630
  return startTestsNode(paths, config);
648
631
  }
649
632
  function clearModuleMocks() {
650
- const { clearMocks, mockReset, restoreMocks } = getWorkerState().config;
633
+ const { clearMocks, mockReset, restoreMocks, unstubEnvs, unstubGlobals } = getWorkerState().config;
651
634
  if (restoreMocks)
652
635
  vi.restoreAllMocks();
653
636
  else if (mockReset)
654
637
  vi.resetAllMocks();
655
638
  else if (clearMocks)
656
639
  vi.clearAllMocks();
640
+ if (unstubEnvs)
641
+ vi.unstubAllEnvs();
642
+ if (unstubGlobals)
643
+ vi.unstubAllGlobals();
657
644
  }
658
645
 
659
646
  export { setupGlobalEnv as a, startTests as s, withEnv as w };