vitest 0.28.4 → 0.29.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 (46) hide show
  1. package/LICENSE.md +1 -1
  2. package/coverage.d.ts +1 -0
  3. package/dist/browser.d.ts +2 -1
  4. package/dist/browser.js +4 -4
  5. package/dist/child.js +89 -0
  6. package/dist/{chunk-api-setup.ec61b167.js → chunk-api-setup.d9eccaeb.js} +5 -5
  7. package/dist/{chunk-env-node.ffd1183b.js → chunk-env-node.affdd278.js} +1 -2
  8. package/dist/{chunk-install-pkg.13d8e7be.js → chunk-install-pkg.ea1a5ef4.js} +9 -8
  9. package/dist/chunk-integrations-coverage.e0a6acd2.js +51 -0
  10. package/dist/{chunk-integrations-globals.aacbac4d.js → chunk-integrations-globals.b56fcb06.js} +8 -8
  11. package/dist/{chunk-integrations-run-once.38756e30.js → chunk-integrations-run-once.9012f759.js} +1 -1
  12. package/dist/{chunk-integrations-utils.dae69d89.js → chunk-integrations-utils.233d6a3b.js} +2 -2
  13. package/dist/{chunk-node-git.d9ad64ab.js → chunk-node-git.ed5bded8.js} +1 -2
  14. package/dist/{chunk-node-pkg.94145502.js → chunk-node-pkg.88e7e848.js} +4423 -270
  15. package/dist/{chunk-runtime-mocker.eb0c265c.js → chunk-runtime-mocker.a048e92d.js} +83 -47
  16. package/dist/chunk-runtime-rpc.971b3848.js +61 -0
  17. package/dist/{chunk-runtime-setup.7dfc1a6a.js → chunk-runtime-setup.992bb661.js} +2 -2
  18. package/dist/{chunk-snapshot-env.6457638e.js → chunk-snapshot-env.a347d647.js} +2 -2
  19. package/dist/{chunk-utils-base.904102a8.js → chunk-utils-base.81f83dbd.js} +15 -1
  20. package/dist/{chunk-utils-global.442d1d33.js → chunk-utils-global.727b6d25.js} +1 -7
  21. package/dist/{chunk-utils-import.0402c9db.js → chunk-utils-import.ec15dcad.js} +18 -29
  22. package/dist/{chunk-utils-tasks.a9a8d8e1.js → chunk-utils-tasks.b41c8284.js} +14 -10
  23. package/dist/cli-wrapper.js +1 -2
  24. package/dist/cli.js +12 -11
  25. package/dist/config.cjs +1 -1
  26. package/dist/config.d.ts +8 -7
  27. package/dist/config.js +1 -1
  28. package/dist/coverage.d.ts +142 -0
  29. package/dist/coverage.js +49 -0
  30. package/dist/entry.js +51 -84
  31. package/dist/environments.d.ts +2 -1
  32. package/dist/environments.js +1 -1
  33. package/dist/index.d.ts +4 -3
  34. package/dist/index.js +9 -9
  35. package/dist/loader.js +2 -2
  36. package/dist/node.d.ts +9 -10
  37. package/dist/node.js +14 -12
  38. package/dist/runners.d.ts +4 -1
  39. package/dist/runners.js +221 -13
  40. package/dist/{types-aac763a5.d.ts → types-7cd96283.d.ts} +164 -39
  41. package/dist/{vendor-index.618ca5a1.js → vendor-index.2cbcdd1e.js} +18 -13
  42. package/dist/worker.js +14 -56
  43. package/package.json +16 -10
  44. package/dist/chunk-integrations-coverage.48e6286b.js +0 -3993
  45. package/dist/chunk-runtime-rpc.9c0386cc.js +0 -31
  46. package/dist/runners-chunk.js +0 -215
@@ -1,12 +1,16 @@
1
- import { ViteNodeRunner } from 'vite-node/client';
2
- import { isInternalRequest } from 'vite-node/utils';
3
- import { resolve, isAbsolute, dirname, join, basename, extname, normalize } from 'pathe';
1
+ import { pathToFileURL } from 'node:url';
2
+ import { ModuleCacheMap, ViteNodeRunner } from 'vite-node/client';
3
+ import { isInternalRequest, isPrimitive } from 'vite-node/utils';
4
+ import { isAbsolute, dirname, join, basename, extname, resolve, normalize, relative } from 'pathe';
4
5
  import { i as isNodeBuiltin } from './vendor-index.bdee400f.js';
5
- import { g as getWorkerState, b as getCurrentEnvironment } from './chunk-utils-global.442d1d33.js';
6
+ import { processError } from '@vitest/runner/utils';
7
+ import { g as getWorkerState, b as getCurrentEnvironment } from './chunk-utils-global.727b6d25.js';
8
+ import { d as distDir } from './chunk-constants.797d3ebf.js';
6
9
  import { existsSync, readdirSync } from 'node:fs';
7
10
  import { getColors, getType } from '@vitest/utils';
8
- import { g as getAllMockableProperties } from './chunk-utils-base.904102a8.js';
9
- import { d as distDir } from './chunk-constants.797d3ebf.js';
11
+ import { e as getAllMockableProperties } from './chunk-utils-base.81f83dbd.js';
12
+ import { spyOn } from '@vitest/spy';
13
+ import { r as rpc } from './chunk-runtime-rpc.971b3848.js';
10
14
 
11
15
  class RefTracker {
12
16
  constructor() {
@@ -30,21 +34,26 @@ function isSpecialProp(prop, parentType) {
30
34
  return parentType.includes("Function") && typeof prop === "string" && ["arguments", "callee", "caller", "length", "name"].includes(prop);
31
35
  }
32
36
  const _VitestMocker = class {
33
- constructor(runner) {
34
- this.runner = runner;
37
+ constructor(executor) {
38
+ this.executor = executor;
35
39
  this.resolveCache = /* @__PURE__ */ new Map();
36
40
  }
37
41
  get root() {
38
- return this.runner.options.root;
42
+ return this.executor.options.root;
39
43
  }
40
44
  get base() {
41
- return this.runner.options.base;
45
+ return this.executor.options.base;
42
46
  }
43
47
  get mockMap() {
44
- return this.runner.options.mockMap;
48
+ return this.executor.options.mockMap;
45
49
  }
46
50
  get moduleCache() {
47
- return this.runner.moduleCache;
51
+ return this.executor.moduleCache;
52
+ }
53
+ deleteCachedItem(id) {
54
+ const mockId = this.getMockPath(id);
55
+ if (this.moduleCache.has(mockId))
56
+ this.moduleCache.delete(mockId);
48
57
  }
49
58
  getSuiteFilepath() {
50
59
  return getWorkerState().filepath || "global";
@@ -59,7 +68,7 @@ const _VitestMocker = class {
59
68
  };
60
69
  }
61
70
  async resolvePath(rawId, importer) {
62
- const [id, fsPath] = await this.runner.resolveUrl(rawId, importer);
71
+ const [id, fsPath] = await this.executor.resolveUrl(rawId, importer);
63
72
  const external = !isAbsolute(fsPath) || fsPath.includes("/node_modules/") ? rawId : null;
64
73
  return {
65
74
  id,
@@ -87,7 +96,7 @@ const _VitestMocker = class {
87
96
  exports = await mock();
88
97
  } catch (err) {
89
98
  const vitestError = new Error(
90
- '[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'
99
+ '[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'
91
100
  );
92
101
  vitestError.cause = err;
93
102
  throw vitestError;
@@ -103,6 +112,8 @@ const _VitestMocker = class {
103
112
  if (target instanceof Promise)
104
113
  return target.then.bind(target);
105
114
  } else if (!(prop in target)) {
115
+ if (prop === "__esModule")
116
+ return void 0;
106
117
  const c = getColors();
107
118
  throw new Error(
108
119
  `[vitest] No "${String(prop)}" export is defined on the "${mockpath}" mock. Did you forget to return it from "vi.mock"?
@@ -155,12 +166,6 @@ ${c.green(`vi.mock("${mockpath}", async () => {
155
166
  return existsSync(fullPath) ? fullPath : null;
156
167
  }
157
168
  mockObject(object, mockExports = {}) {
158
- if (!_VitestMocker.spyModule) {
159
- throw new Error(
160
- "Error: Spy module is not defined. This is likely an internal bug in Vitest. Please report it to https://github.com/vitest-dev/vitest/issues"
161
- );
162
- }
163
- const spyModule = _VitestMocker.spyModule;
164
169
  const finalizers = new Array();
165
170
  const refs = new RefTracker();
166
171
  const define = (container, key, value) => {
@@ -203,7 +208,7 @@ ${c.green(`vi.mock("${mockpath}", async () => {
203
208
  if (!define(newContainer, property, isFunction ? value : {}))
204
209
  continue;
205
210
  if (isFunction) {
206
- spyModule.spyOn(newContainer, property).mockImplementation(() => void 0);
211
+ spyOn(newContainer, property).mockImplementation(() => void 0);
207
212
  Object.defineProperty(newContainer[property], "length", { value: 0 });
208
213
  }
209
214
  refs.track(value, newContainer[property]);
@@ -222,9 +227,7 @@ ${c.green(`vi.mock("${mockpath}", async () => {
222
227
  const mock = this.mockMap.get(suitefile);
223
228
  if (mock && id in mock)
224
229
  delete mock[id];
225
- const mockId = this.getMockPath(id);
226
- if (this.moduleCache.get(mockId))
227
- this.moduleCache.delete(mockId);
230
+ this.deleteCachedItem(id);
228
231
  }
229
232
  mockPath(originalId, path, external, factory) {
230
233
  const suitefile = this.getSuiteFilepath();
@@ -235,10 +238,11 @@ ${c.green(`vi.mock("${mockpath}", async () => {
235
238
  resolves[id] = originalId;
236
239
  this.mockMap.set(suitefile, mocks);
237
240
  this.resolveCache.set(suitefile, resolves);
241
+ this.deleteCachedItem(id);
238
242
  }
239
243
  async importActual(rawId, importee) {
240
244
  const { id, fsPath } = await this.resolvePath(rawId, importee);
241
- const result = await this.runner.cachedRequest(id, fsPath, [importee]);
245
+ const result = await this.executor.cachedRequest(id, fsPath, [importee]);
242
246
  return result;
243
247
  }
244
248
  async importMock(rawId, importee) {
@@ -248,17 +252,12 @@ ${c.green(`vi.mock("${mockpath}", async () => {
248
252
  if (mock === void 0)
249
253
  mock = this.resolveMockPath(fsPath, external);
250
254
  if (mock === null) {
251
- const mod = await this.runner.cachedRequest(id, fsPath, [importee]);
255
+ const mod = await this.executor.cachedRequest(id, fsPath, [importee]);
252
256
  return this.mockObject(mod);
253
257
  }
254
258
  if (typeof mock === "function")
255
259
  return this.callFunctionMock(fsPath, mock);
256
- return this.runner.dependencyRequest(mock, mock, [importee]);
257
- }
258
- async initializeSpyModule() {
259
- if (_VitestMocker.spyModule)
260
- return;
261
- _VitestMocker.spyModule = await this.runner.executeId(_VitestMocker.spyModulePath);
260
+ return this.executor.dependencyRequest(mock, mock, [importee]);
262
261
  }
263
262
  async requestWithMock(url, callstack) {
264
263
  if (_VitestMocker.pendingIds.length)
@@ -272,7 +271,7 @@ ${c.green(`vi.mock("${mockpath}", async () => {
272
271
  return cache.exports;
273
272
  const exports = {};
274
273
  this.moduleCache.set(mockPath, { exports });
275
- const mod = await this.runner.directRequest(url, url, callstack);
274
+ const mod = await this.executor.directRequest(url, url, callstack);
276
275
  this.mockObject(mod, exports);
277
276
  return exports;
278
277
  }
@@ -295,18 +294,55 @@ ${c.green(`vi.mock("${mockpath}", async () => {
295
294
  };
296
295
  let VitestMocker = _VitestMocker;
297
296
  VitestMocker.pendingIds = [];
298
- VitestMocker.spyModulePath = resolve(distDir, "spy.js");
299
297
 
300
- async function executeInViteNode(options) {
301
- const runner = new VitestRunner(options);
298
+ async function createVitestExecutor(options) {
299
+ const runner = new VitestExecutor(options);
302
300
  await runner.executeId("/@vite/env");
303
- await runner.mocker.initializeSpyModule();
304
- const result = [];
305
- for (const file of options.files)
306
- result.push(await runner.executeFile(file));
307
- return result;
301
+ return runner;
302
+ }
303
+ let _viteNode;
304
+ const moduleCache = new ModuleCacheMap();
305
+ const mockMap = /* @__PURE__ */ new Map();
306
+ async function startViteNode(ctx) {
307
+ if (_viteNode)
308
+ return _viteNode;
309
+ const { config } = ctx;
310
+ const processExit = process.exit;
311
+ process.exit = (code = process.exitCode || 0) => {
312
+ const error = new Error(`process.exit called with "${code}"`);
313
+ rpc().onWorkerExit(error, code);
314
+ return processExit(code);
315
+ };
316
+ function catchError(err, type) {
317
+ var _a;
318
+ const worker = getWorkerState();
319
+ const error = processError(err);
320
+ if (worker.filepath && !isPrimitive(error)) {
321
+ error.VITEST_TEST_NAME = (_a = worker.current) == null ? void 0 : _a.name;
322
+ error.VITEST_TEST_PATH = relative(config.root, worker.filepath);
323
+ }
324
+ rpc().onUnhandledError(error, type);
325
+ }
326
+ process.on("uncaughtException", (e) => catchError(e, "Uncaught Exception"));
327
+ process.on("unhandledRejection", (e) => catchError(e, "Unhandled Rejection"));
328
+ const executor = await createVitestExecutor({
329
+ fetchModule(id) {
330
+ return rpc().fetch(id, ctx.environment.name);
331
+ },
332
+ resolveId(id, importer) {
333
+ return rpc().resolveId(id, importer, ctx.environment.name);
334
+ },
335
+ moduleCache,
336
+ mockMap,
337
+ interopDefault: config.deps.interopDefault,
338
+ root: config.root,
339
+ base: config.base
340
+ });
341
+ const { run } = await import(pathToFileURL(resolve(distDir, "entry.js")).href);
342
+ _viteNode = { run, executor };
343
+ return _viteNode;
308
344
  }
309
- class VitestRunner extends ViteNodeRunner {
345
+ class VitestExecutor extends ViteNodeRunner {
310
346
  constructor(options) {
311
347
  super(options);
312
348
  this.options = options;
@@ -323,10 +359,10 @@ class VitestRunner extends ViteNodeRunner {
323
359
  const environment = getCurrentEnvironment();
324
360
  return environment === "node" ? !isNodeBuiltin(id) : !id.startsWith("node:");
325
361
  }
326
- async resolveUrl(id, importee) {
327
- if (importee && importee.startsWith("mock:"))
328
- importee = importee.slice(5);
329
- return super.resolveUrl(id, importee);
362
+ async resolveUrl(id, importer) {
363
+ if (importer && importer.startsWith("mock:"))
364
+ importer = importer.slice(5);
365
+ return super.resolveUrl(id, importer);
330
366
  }
331
367
  async dependencyRequest(id, fsPath, callstack) {
332
368
  const mocked = await this.mocker.requestWithMock(fsPath, callstack);
@@ -345,4 +381,4 @@ class VitestRunner extends ViteNodeRunner {
345
381
  }
346
382
  }
347
383
 
348
- export { VitestRunner as V, executeInViteNode as e };
384
+ export { VitestExecutor as V, mockMap as a, moduleCache as m, startViteNode as s };
@@ -0,0 +1,61 @@
1
+ import { getSafeTimers } from '@vitest/utils';
2
+ import { g as getWorkerState } from './chunk-utils-global.727b6d25.js';
3
+
4
+ const { get } = Reflect;
5
+ const safeRandom = Math.random;
6
+ function withSafeTimers(fn) {
7
+ const { setTimeout, clearTimeout, nextTick, setImmediate, clearImmediate } = getSafeTimers();
8
+ const currentSetTimeout = globalThis.setTimeout;
9
+ const currentClearTimeout = globalThis.clearTimeout;
10
+ const currentRandom = globalThis.Math.random;
11
+ const currentNextTick = globalThis.process.nextTick;
12
+ const currentSetImmediate = globalThis.setImmediate;
13
+ const currentClearImmediate = globalThis.clearImmediate;
14
+ try {
15
+ globalThis.setTimeout = setTimeout;
16
+ globalThis.clearTimeout = clearTimeout;
17
+ globalThis.Math.random = safeRandom;
18
+ globalThis.process.nextTick = nextTick;
19
+ globalThis.setImmediate = setImmediate;
20
+ globalThis.clearImmediate = clearImmediate;
21
+ const result = fn();
22
+ return result;
23
+ } finally {
24
+ globalThis.setTimeout = currentSetTimeout;
25
+ globalThis.clearTimeout = currentClearTimeout;
26
+ globalThis.Math.random = currentRandom;
27
+ globalThis.setImmediate = currentSetImmediate;
28
+ globalThis.clearImmediate = currentClearImmediate;
29
+ nextTick(() => {
30
+ globalThis.process.nextTick = currentNextTick;
31
+ });
32
+ }
33
+ }
34
+ const promises = /* @__PURE__ */ new Set();
35
+ const rpcDone = () => {
36
+ if (!promises.size)
37
+ return;
38
+ const awaitable = Array.from(promises);
39
+ return Promise.all(awaitable);
40
+ };
41
+ const rpc = () => {
42
+ const { rpc: rpc2 } = getWorkerState();
43
+ return new Proxy(rpc2, {
44
+ get(target, p, handler) {
45
+ const sendCall = get(target, p, handler);
46
+ const safeSendCall = (...args) => withSafeTimers(async () => {
47
+ const result = sendCall(...args);
48
+ promises.add(result);
49
+ try {
50
+ return await result;
51
+ } finally {
52
+ promises.delete(result);
53
+ }
54
+ });
55
+ safeSendCall.asEvent = sendCall.asEvent;
56
+ return safeSendCall;
57
+ }
58
+ });
59
+ };
60
+
61
+ export { rpcDone as a, rpc as r };
@@ -1,5 +1,5 @@
1
1
  import { setSafeTimers } from '@vitest/utils';
2
- import { a as resetRunOnceCounter } from './chunk-integrations-run-once.38756e30.js';
2
+ import { a as resetRunOnceCounter } from './chunk-integrations-run-once.9012f759.js';
3
3
 
4
4
  let globalSetup = false;
5
5
  async function setupCommonEnv(config) {
@@ -10,7 +10,7 @@ async function setupCommonEnv(config) {
10
10
  globalSetup = true;
11
11
  setSafeTimers();
12
12
  if (config.globals)
13
- (await import('./chunk-integrations-globals.aacbac4d.js')).registerApiGlobally();
13
+ (await import('./chunk-integrations-globals.b56fcb06.js')).registerApiGlobally();
14
14
  }
15
15
  function setupDefines(defines) {
16
16
  for (const key in defines)
@@ -2,10 +2,10 @@ let _snapshotEnvironment;
2
2
  function setupSnapshotEnvironment(environment) {
3
3
  _snapshotEnvironment = environment;
4
4
  }
5
- function getSnapshotEnironment() {
5
+ function getSnapshotEnvironment() {
6
6
  if (!_snapshotEnvironment)
7
7
  throw new Error("Snapshot environment is not setup");
8
8
  return _snapshotEnvironment;
9
9
  }
10
10
 
11
- export { getSnapshotEnironment as g, setupSnapshotEnvironment as s };
11
+ export { getSnapshotEnvironment as g, setupSnapshotEnvironment as s };
@@ -6,6 +6,14 @@ function collectOwnProperties(obj, collector) {
6
6
  Object.getOwnPropertyNames(obj).forEach(collect);
7
7
  Object.getOwnPropertySymbols(obj).forEach(collect);
8
8
  }
9
+ function groupBy(collection, iteratee) {
10
+ return collection.reduce((acc, item) => {
11
+ const key = iteratee(item);
12
+ acc[key] || (acc[key] = []);
13
+ acc[key].push(item);
14
+ return acc;
15
+ }, {});
16
+ }
9
17
  function getAllMockableProperties(obj, isModule) {
10
18
  const allProps = /* @__PURE__ */ new Map();
11
19
  let curr = obj;
@@ -70,5 +78,11 @@ function isMergeableObject(item) {
70
78
  function stdout() {
71
79
  return console._stdout || process.stdout;
72
80
  }
81
+ function getEnvironmentTransformMode(config, environment) {
82
+ var _a, _b;
83
+ if (!((_b = (_a = config.deps) == null ? void 0 : _a.experimentalOptimizer) == null ? void 0 : _b.enabled))
84
+ return void 0;
85
+ return environment === "happy-dom" || environment === "jsdom" ? "web" : "ssr";
86
+ }
73
87
 
74
- export { noop as a, stdout as b, deepMerge as d, getAllMockableProperties as g, isObject as i, notNullish as n, slash as s, toArray as t };
88
+ export { getEnvironmentTransformMode as a, noop as b, stdout as c, deepMerge as d, getAllMockableProperties as e, groupBy as g, isObject as i, notNullish as n, slash as s, toArray as t };
@@ -63,11 +63,5 @@ function getCallLastIndex(code) {
63
63
  }
64
64
  return null;
65
65
  }
66
- class AggregateErrorPonyfill extends Error {
67
- constructor(errors, message = "") {
68
- super(message);
69
- this.errors = [...errors];
70
- }
71
- }
72
66
 
73
- export { AggregateErrorPonyfill as A, getCallLastIndex as a, getCurrentEnvironment as b, relativePath as c, removeUndefinedValues as d, isWindows as e, getWorkerState as g, isRunningInBenchmark as i, resetModules as r };
67
+ export { getCallLastIndex as a, getCurrentEnvironment as b, relativePath as c, removeUndefinedValues as d, isWindows as e, getWorkerState as g, isRunningInBenchmark as i, resetModules as r };
@@ -1,16 +1,16 @@
1
1
  import { getCurrentSuite } from '@vitest/runner';
2
2
  import { createChainable, getNames } from '@vitest/runner/utils';
3
- import { getSafeTimers, noop } from '@vitest/utils';
4
- import { g as getWorkerState, i as isRunningInBenchmark, a as getCallLastIndex, b as getCurrentEnvironment, r as resetModules } from './chunk-utils-global.442d1d33.js';
3
+ import { getSafeTimers, noop, createSimpleStackTrace } from '@vitest/utils';
4
+ import { g as getWorkerState, i as isRunningInBenchmark, a as getCallLastIndex, b as getCurrentEnvironment, r as resetModules } from './chunk-utils-global.727b6d25.js';
5
5
  import * as chai$1 from 'chai';
6
6
  import { expect } from 'chai';
7
7
  import { c as commonjsGlobal } from './vendor-_commonjsHelpers.addc3445.js';
8
8
  import { equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, JestAsymmetricMatchers, GLOBAL_EXPECT, getState, setState } from '@vitest/expect';
9
- import { r as rpc } from './chunk-runtime-rpc.9c0386cc.js';
9
+ import { r as rpc } from './chunk-runtime-rpc.971b3848.js';
10
10
  import { join, dirname } from 'pathe';
11
- import { g as getSnapshotEnironment } from './chunk-snapshot-env.6457638e.js';
12
- import { i as isObject, s as slash } from './chunk-utils-base.904102a8.js';
13
- import { p as positionToOffset, o as offsetToLineNumber, l as lineSplitRE, a as parseStacktrace, g as getFullName, b as parseSingleStack } from './chunk-utils-tasks.a9a8d8e1.js';
11
+ import { g as getSnapshotEnvironment } from './chunk-snapshot-env.a347d647.js';
12
+ import { i as isObject } from './chunk-utils-base.81f83dbd.js';
13
+ import { p as positionToOffset, o as offsetToLineNumber, l as lineSplitRE, a as parseErrorStacktrace, g as getFullName, b as parseSingleStack } from './chunk-utils-tasks.b41c8284.js';
14
14
  import require$$0 from 'util';
15
15
  import { spyOn, fn, isMockFunction, spies } from '@vitest/spy';
16
16
 
@@ -2568,7 +2568,7 @@ const addSerializer = (plugin) => {
2568
2568
  const getSerializers = () => PLUGINS;
2569
2569
 
2570
2570
  const SNAPSHOT_VERSION = "1";
2571
- const writeSnapshotVersion = () => `// Vitest Snapshot v${SNAPSHOT_VERSION}`;
2571
+ const writeSnapshotVersion = () => `// Vitest Snapshot v${SNAPSHOT_VERSION}, https://vitest.dev/guide/snapshot.html`;
2572
2572
  const testNameToKey = (testName, count) => `${testName} ${count}`;
2573
2573
  const keyToTestName = (key) => {
2574
2574
  if (!/ \d+$/.test(key))
@@ -2618,7 +2618,7 @@ function printBacktickString(str) {
2618
2618
  }
2619
2619
  async function ensureDirectoryExists(filePath) {
2620
2620
  try {
2621
- const environment = getSnapshotEnironment();
2621
+ const environment = getSnapshotEnvironment();
2622
2622
  await environment.prepareDirectory(join(dirname(filePath)));
2623
2623
  } catch {
2624
2624
  }
@@ -2627,7 +2627,7 @@ function normalizeNewlines(string) {
2627
2627
  return string.replace(/\r\n|\r/g, "\n");
2628
2628
  }
2629
2629
  async function saveSnapshotFile(snapshotData, snapshotPath) {
2630
- const environment = getSnapshotEnironment();
2630
+ const environment = getSnapshotEnvironment();
2631
2631
  const snapshots = Object.keys(snapshotData).sort(naturalCompare$1.exports).map(
2632
2632
  (key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`
2633
2633
  );
@@ -2699,7 +2699,7 @@ function deepMergeSnapshot(target, source) {
2699
2699
  }
2700
2700
 
2701
2701
  async function saveInlineSnapshots(snapshots) {
2702
- const environment = getSnapshotEnironment();
2702
+ const environment = getSnapshotEnvironment();
2703
2703
  const MagicString = (await import('./chunk-magic-string.3a794426.js')).default;
2704
2704
  const files = new Set(snapshots.map((i) => i.file));
2705
2705
  await Promise.all(Array.from(files).map(async (file) => {
@@ -2815,10 +2815,10 @@ class SnapshotState {
2815
2815
  printBasicPrototype: false,
2816
2816
  ...options.snapshotFormat
2817
2817
  };
2818
- this._environment = getSnapshotEnironment();
2818
+ this._environment = getSnapshotEnvironment();
2819
2819
  }
2820
2820
  static async create(testFilePath, options) {
2821
- const environment = getSnapshotEnironment();
2821
+ const environment = getSnapshotEnvironment();
2822
2822
  const snapshotPath = await environment.resolvePath(testFilePath);
2823
2823
  const content = await environment.readSnapshotFile(snapshotPath);
2824
2824
  return new SnapshotState(testFilePath, snapshotPath, content, options);
@@ -2839,9 +2839,7 @@ class SnapshotState {
2839
2839
  _addSnapshot(key, receivedSerialized, options) {
2840
2840
  this._dirty = true;
2841
2841
  if (options.isInline) {
2842
- const error = options.error || new Error("Unknown error");
2843
- const stacks = parseStacktrace(error, true);
2844
- stacks.forEach((i) => i.file = slash(i.file));
2842
+ const stacks = parseErrorStacktrace(options.error || new Error("snapshot"), true);
2845
2843
  const stack = this._inferInlineSnapshotStack(stacks);
2846
2844
  if (!stack) {
2847
2845
  throw new Error(
@@ -3271,19 +3269,6 @@ Object.defineProperty(globalThis, GLOBAL_EXPECT, {
3271
3269
  configurable: true
3272
3270
  });
3273
3271
 
3274
- function createSimpleStackTrace(options) {
3275
- const { message = "error", stackTraceLimit = 1 } = options || {};
3276
- const limit = Error.stackTraceLimit;
3277
- const prepareStackTrace = Error.prepareStackTrace;
3278
- Error.stackTraceLimit = stackTraceLimit;
3279
- Error.prepareStackTrace = (e) => e.stack;
3280
- const err = new Error(message);
3281
- const stackTrace = err.stack || "";
3282
- Error.prepareStackTrace = prepareStackTrace;
3283
- Error.stackTraceLimit = limit;
3284
- return stackTrace;
3285
- }
3286
-
3287
3272
  /**
3288
3273
  * A reference to the global object
3289
3274
  *
@@ -6014,7 +5999,11 @@ class VitestUtils {
6014
5999
  this._mocker = typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : null;
6015
6000
  this._mockedDate = null;
6016
6001
  if (!this._mocker) {
6017
- const errorMsg = 'Vitest was initialized with native Node instead of Vite Node.\n\nOne of the following is possible:\n- "vitest" is imported outside of your tests (in that case, use "vitest/node" or import.meta.vitest)\n- "vitest" is imported inside "globalSetup" (use "setupFiles", because "globalSetup" runs in a different context)\n- Your dependency inside "node_modules" imports "vitest" directly (in that case, inline that dependency, using "deps.inline" config)\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n';
6002
+ const errorMsg = `Vitest was initialized with native Node instead of Vite Node.
6003
+
6004
+ It's possible that you are importing "vitest" directly inside "globalSetup". In that case, use "setupFiles" because "globalSetup" runs in a different context.
6005
+ Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues
6006
+ `;
6018
6007
  throw new Error(errorMsg);
6019
6008
  }
6020
6009
  const workerState = getWorkerState();
@@ -1,11 +1,11 @@
1
1
  import { getNames, getTests } from '@vitest/runner/utils';
2
2
  import { resolve } from 'pathe';
3
- import { n as notNullish } from './chunk-utils-base.904102a8.js';
3
+ import { n as notNullish } from './chunk-utils-base.81f83dbd.js';
4
4
 
5
5
  function hasFailedSnapshot(suite) {
6
6
  return getTests(suite).some((s) => {
7
7
  var _a, _b;
8
- return (_b = (_a = s.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.some((e) => e.message.match(/Snapshot .* mismatched/));
8
+ return (_b = (_a = s.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.some((e) => e && e.message && e.message.match(/Snapshot .* mismatched/));
9
9
  });
10
10
  }
11
11
  function getFullName(task, separator = " > ") {
@@ -58,18 +58,22 @@ function parseSingleStack(raw) {
58
58
  column: parseInt(columnNumber)
59
59
  };
60
60
  }
61
- function parseStacktrace(e, full = false) {
61
+ function parseStacktrace(stack, full = false) {
62
+ const stackFrames = stack.split("\n").map((raw) => {
63
+ const stack2 = parseSingleStack(raw);
64
+ if (!stack2 || !full && stackIgnorePatterns.some((p) => stack2.file.match(p)))
65
+ return null;
66
+ return stack2;
67
+ }).filter(notNullish);
68
+ return stackFrames;
69
+ }
70
+ function parseErrorStacktrace(e, full = false) {
62
71
  if (!e)
63
72
  return [];
64
73
  if (e.stacks)
65
74
  return e.stacks;
66
75
  const stackStr = e.stack || e.stackStr || "";
67
- const stackFrames = stackStr.split("\n").map((raw) => {
68
- const stack = parseSingleStack(raw);
69
- if (!stack || !full && stackIgnorePatterns.some((p) => stack.file.match(p)))
70
- return null;
71
- return stack;
72
- }).filter(notNullish);
76
+ const stackFrames = parseStacktrace(stackStr, full);
73
77
  e.stacks = stackFrames;
74
78
  return stackFrames;
75
79
  }
@@ -100,4 +104,4 @@ function offsetToLineNumber(source, offset) {
100
104
  return line + 1;
101
105
  }
102
106
 
103
- export { parseStacktrace as a, parseSingleStack as b, getFullName as g, hasFailedSnapshot as h, lineSplitRE as l, offsetToLineNumber as o, positionToOffset as p };
107
+ export { parseErrorStacktrace as a, parseSingleStack as b, getFullName as g, hasFailedSnapshot as h, lineSplitRE as l, offsetToLineNumber as o, positionToOffset as p };
@@ -1,6 +1,6 @@
1
1
  import { fileURLToPath } from 'url';
2
2
  import c from 'picocolors';
3
- import { e as execa } from './vendor-index.618ca5a1.js';
3
+ import { e as execa } from './vendor-index.2cbcdd1e.js';
4
4
  import { E as EXIT_CODE_RESTART } from './chunk-constants.797d3ebf.js';
5
5
  import 'node:buffer';
6
6
  import 'node:path';
@@ -11,7 +11,6 @@ import 'path';
11
11
  import './vendor-_commonjsHelpers.addc3445.js';
12
12
  import 'fs';
13
13
  import 'node:url';
14
- import 'os';
15
14
  import 'node:os';
16
15
  import 'assert';
17
16
  import 'events';
package/dist/cli.js CHANGED
@@ -1,33 +1,33 @@
1
1
  import { normalize } from 'pathe';
2
2
  import cac from 'cac';
3
3
  import c from 'picocolors';
4
- import { v as version, s as startVitest, d as divider } from './chunk-node-pkg.94145502.js';
4
+ import { v as version, s as startVitest, d as divider } from './chunk-node-pkg.88e7e848.js';
5
5
  import './chunk-constants.797d3ebf.js';
6
6
  import 'node:url';
7
7
  import './chunk-utils-env.860d90c2.js';
8
8
  import 'std-env';
9
- import './chunk-integrations-coverage.48e6286b.js';
9
+ import './chunk-integrations-coverage.e0a6acd2.js';
10
10
  import 'local-pkg';
11
- import 'util';
12
- import 'path';
13
- import './chunk-env-node.ffd1183b.js';
11
+ import './chunk-env-node.affdd278.js';
14
12
  import 'node:console';
15
13
  import 'vite';
16
14
  import 'node:path';
17
15
  import 'node:process';
18
16
  import 'node:fs';
17
+ import 'path';
19
18
  import 'os';
19
+ import 'util';
20
20
  import 'stream';
21
21
  import 'events';
22
22
  import 'fs';
23
23
  import './vendor-_commonjsHelpers.addc3445.js';
24
24
  import 'vite-node/client';
25
25
  import 'vite-node/server';
26
- import './chunk-utils-global.442d1d33.js';
26
+ import './chunk-utils-global.727b6d25.js';
27
27
  import '@vitest/runner/utils';
28
28
  import '@vitest/utils';
29
29
  import 'node:fs/promises';
30
- import './vendor-index.618ca5a1.js';
30
+ import './vendor-index.2cbcdd1e.js';
31
31
  import 'node:buffer';
32
32
  import 'node:child_process';
33
33
  import 'child_process';
@@ -38,12 +38,13 @@ import 'source-map';
38
38
  import 'module';
39
39
  import 'acorn';
40
40
  import 'acorn-walk';
41
+ import 'node:v8';
42
+ import './vendor-index.783e7f3e.js';
43
+ import './chunk-utils-base.81f83dbd.js';
41
44
  import 'node:worker_threads';
42
45
  import 'tinypool';
43
- import './vendor-index.783e7f3e.js';
44
46
  import 'perf_hooks';
45
- import './chunk-utils-base.904102a8.js';
46
- import './chunk-utils-tasks.a9a8d8e1.js';
47
+ import './chunk-utils-tasks.b41c8284.js';
47
48
  import 'crypto';
48
49
  import 'vite-node/utils';
49
50
  import '@vitest/utils/diff';
@@ -53,7 +54,7 @@ import 'strip-literal';
53
54
  import 'readline';
54
55
 
55
56
  const cli = cac("vitest");
56
- cli.version(version).option("-r, --root <path>", "Root path").option("-c, --config <path>", "Path to config file").option("-u, --update", "Update snapshot").option("-w, --watch", "Enable watch mode").option("-t, --testNamePattern <pattern>", "Run tests with full names matching the specified regexp pattern").option("--dir <path>", "Base directory to scan for the test files").option("--ui", "Enable UI").option("--open", "Open UI automatically (default: !process.env.CI))").option("--api [api]", "Serve API, available options: --api.port <port>, --api.host [host] and --api.strictPort").option("--threads", "Enabled threads (default: true)").option("--silent", "Silent console output from tests").option("--isolate", "Isolate environment for each test file (default: true)").option("--reporter <name>", "Specify reporters").option("--outputDiffMaxSize <length>", "Object diff output max size (default: 10000)").option("--outputDiffMaxLines <length>", "Max lines in diff output window (default: 50)").option("--outputTruncateLength <length>", "Diff output line length (default: 80)").option("--outputDiffLines <lines>", "Number of lines in single diff (default: 15)").option("--outputFile <filename/-s>", "Write test results to a file when supporter reporter is also specified, use cac's dot notation for individual outputs of multiple reporters").option("--coverage", "Enable coverage report").option("--run", "Disable watch mode").option("--mode <name>", "Override Vite mode (default: test)").option("--globals", "Inject apis globally").option("--dom", "Mock browser api with happy-dom").option("--browser", "Run tests in browser").option("--environment <env>", "Specify runner environment (default: node)").option("--passWithNoTests", "Pass when no tests found").option("--logHeapUsage", "Show the size of heap for each test").option("--allowOnly", "Allow tests and suites that are marked as only (default: !process.env.CI)").option("--dangerouslyIgnoreUnhandledErrors", "Ignore any unhandled errors that occur").option("--shard <shard>", "Test suite shard to execute in a format of <index>/<count>").option("--changed [since]", "Run tests that are affected by the changed files (default: false)").option("--sequence <options>", "Define in what order to run tests (use --sequence.shuffle to run tests in random order)").option("--segfaultRetry <times>", "Return tests on segment fault (default: 0)", { default: 0 }).option("--no-color", "Removes colors from the console output").option("--inspect", "Enable Node.js inspector").option("--inspect-brk", "Enable Node.js inspector with break").help();
57
+ cli.version(version).option("-r, --root <path>", "Root path").option("-c, --config <path>", "Path to config file").option("-u, --update", "Update snapshot").option("-w, --watch", "Enable watch mode").option("-t, --testNamePattern <pattern>", "Run tests with full names matching the specified regexp pattern").option("--dir <path>", "Base directory to scan for the test files").option("--ui", "Enable UI").option("--open", "Open UI automatically (default: !process.env.CI))").option("--api [api]", "Serve API, available options: --api.port <port>, --api.host [host] and --api.strictPort").option("--threads", "Enabled threads (default: true)").option("--single-thread", "Run tests inside a single thread, requires --threads (default: false)").option("--silent", "Silent console output from tests").option("--isolate", "Isolate environment for each test file (default: true)").option("--reporter <name>", "Specify reporters").option("--outputDiffMaxSize <length>", "Object diff output max size (default: 10000)").option("--outputDiffMaxLines <length>", "Max lines in diff output window (default: 50)").option("--outputTruncateLength <length>", "Diff output line length (default: 80)").option("--outputDiffLines <lines>", "Number of lines in single diff (default: 15)").option("--outputFile <filename/-s>", "Write test results to a file when supporter reporter is also specified, use cac's dot notation for individual outputs of multiple reporters").option("--coverage", "Enable coverage report").option("--run", "Disable watch mode").option("--mode <name>", "Override Vite mode (default: test)").option("--globals", "Inject apis globally").option("--dom", "Mock browser api with happy-dom").option("--browser", "Run tests in browser").option("--environment <env>", "Specify runner environment (default: node)").option("--passWithNoTests", "Pass when no tests found").option("--logHeapUsage", "Show the size of heap for each test").option("--allowOnly", "Allow tests and suites that are marked as only (default: !process.env.CI)").option("--dangerouslyIgnoreUnhandledErrors", "Ignore any unhandled errors that occur").option("--shard <shard>", "Test suite shard to execute in a format of <index>/<count>").option("--changed [since]", "Run tests that are affected by the changed files (default: false)").option("--sequence <options>", "Define in what order to run tests (use --sequence.shuffle to run tests in random order)").option("--segfaultRetry <times>", "Return tests on segment fault (default: 0)", { default: 0 }).option("--no-color", "Removes colors from the console output").option("--inspect", "Enable Node.js inspector").option("--inspect-brk", "Enable Node.js inspector with break").help();
57
58
  cli.command("run [...filters]").action(run);
58
59
  cli.command("related [...filters]").action(runRelated);
59
60
  cli.command("watch [...filters]").action(watch);
package/dist/config.cjs CHANGED
@@ -30,7 +30,7 @@ const coverageConfigDefaults = {
30
30
  cleanOnRerun: true,
31
31
  reportsDirectory: "./coverage",
32
32
  exclude: defaultCoverageExcludes,
33
- reporter: ["text", "html", "clover", "json"],
33
+ reporter: [["text", {}], ["html", {}], ["clover", {}], ["json", {}]],
34
34
  extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"]
35
35
  };
36
36
  const fakeTimersDefaults = {