vitest 0.0.123 → 0.0.127

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/README.md CHANGED
@@ -4,6 +4,4 @@
4
4
 
5
5
  A blazing fast unit test framework powered by Vite.
6
6
 
7
- > **This project is currently in closed beta exclusively for Sponsors.**<br>
8
- > 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.
9
- > Learn more at [vitest.dev](https://vitest.dev)
7
+ [GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/)
package/dist/cli.js CHANGED
@@ -4,11 +4,11 @@ import { Buffer } from 'buffer';
4
4
  import path from 'path';
5
5
  import childProcess from 'child_process';
6
6
  import process$1 from 'process';
7
- import { m as mergeStream, g as getStream, c as crossSpawn } from './index-6e709f57.js';
7
+ import { m as mergeStream, g as getStream, c as crossSpawn } from './index-4cd25949.js';
8
8
  import require$$0, { constants } from 'os';
9
- import { s as signalExit } from './index-648e7ab2.js';
10
- import { e as ensurePackageInstalled } from './index-250bdca0.js';
11
- import { c as createVitest } from './index-a7ae9662.js';
9
+ import { s as signalExit } from './index-7975be53.js';
10
+ import { e as ensurePackageInstalled } from './index-f0488a5d.js';
11
+ import { c as createVitest } from './index-05648ba5.js';
12
12
  import './_commonjsHelpers-c9e3b764.js';
13
13
  import 'fs';
14
14
  import 'stream';
@@ -18,10 +18,10 @@ import 'url';
18
18
  import 'tty';
19
19
  import 'local-pkg';
20
20
  import 'vite';
21
- import './constants-744cb76d.js';
21
+ import './constants-2cd49e0a.js';
22
22
  import './magic-string.es-94000aea.js';
23
23
  import 'perf_hooks';
24
- import './diff-a0cbb825.js';
24
+ import './diff-711cddf1.js';
25
25
  import 'module';
26
26
  import 'worker_threads';
27
27
  import 'tinypool';
@@ -1700,16 +1700,22 @@ function execa(file, args, options) {
1700
1700
  return mergePromise(spawned, handlePromiseOnce);
1701
1701
  }
1702
1702
 
1703
- var version = "0.0.123";
1703
+ var version = "0.0.127";
1704
1704
 
1705
1705
  const CLOSE_TIMEOUT = 1e3;
1706
1706
  const cli = cac("vitest");
1707
- 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", "watch mode").option("-o, --open", "open UI", { default: false }).option("-t, --testNamePattern <pattern>", "run test names with the specified pattern").option("--api", "listen to port and serve API").option("--threads", "enabled threads", { default: true }).option("--silent", "silent console output from tests").option("--reporter <name>", "reporter").option("--coverage", "use c8 for coverage").option("--run", "do not watch").option("--global", "inject apis globally").option("--dom", "mock browser api with happy-dom").option("--findRelatedTests <filepath>", "run only tests that import specified file").option("--environment <env>", "runner environment", { default: "node" }).option("--passWithNoTests", "pass when no tests found").help();
1707
+ 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", "watch mode").option("-o, --open", "open UI", { default: false }).option("-t, --testNamePattern <pattern>", "run test names with the specified pattern").option("--api", "listen to port and serve API").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>", "reporter").option("--coverage", "use c8 for coverage").option("--run", "do not watch").option("--global", "inject apis globally").option("--dom", "mock browser api with happy-dom").option("--environment <env>", "runner environment", { default: "node" }).option("--passWithNoTests", "pass when no tests found").help();
1708
1708
  cli.command("run [...filters]").action(run);
1709
+ cli.command("related [...filters]").action(runRelated);
1709
1710
  cli.command("watch [...filters]").action(dev);
1710
1711
  cli.command("dev [...filters]").action(dev);
1711
1712
  cli.command("[...filters]").action(dev);
1712
1713
  cli.parse();
1714
+ async function runRelated(relatedFiles, argv) {
1715
+ argv.related = relatedFiles;
1716
+ argv.passWithNoTests ?? (argv.passWithNoTests = true);
1717
+ await dev([], argv);
1718
+ }
1713
1719
  async function dev(cliFilters, argv) {
1714
1720
  if (argv.watch == null)
1715
1721
  argv.watch = !process.env.CI && !argv.run;
@@ -1,5 +1,5 @@
1
1
  import { fileURLToPath } from 'url';
2
- import { k as resolve } from './index-250bdca0.js';
2
+ import { k as resolve } from './index-f0488a5d.js';
3
3
 
4
4
  const distDir = resolve(fileURLToPath(import.meta.url), "../../dist");
5
5
  const defaultInclude = ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"];
@@ -1,5 +1,5 @@
1
1
  import { existsSync, promises } from 'fs';
2
- import { o as notNullish, c, r as relative } from './index-250bdca0.js';
2
+ import { o as notNullish, c, r as relative } from './index-f0488a5d.js';
3
3
 
4
4
  function Diff() {}
5
5
  Diff.prototype = {
@@ -4506,9 +4506,28 @@ function getOriginalPos(map, { line, column }) {
4506
4506
  }
4507
4507
  const stackFnCallRE = /at (.*) \((.+):(\d+):(\d+)\)$/;
4508
4508
  const stackBarePathRE = /at ?(.*) (.+):(\d+):(\d+)$/;
4509
- function parseStack(stack) {
4510
- const lines = stack.split("\n");
4511
- const stackFrames = lines.map((raw) => {
4509
+ async function interpretSourcePos(stackFrames, ctx) {
4510
+ var _a;
4511
+ for (const frame of stackFrames) {
4512
+ const transformResult = (_a = ctx.server.moduleGraph.getModuleById(frame.file)) == null ? void 0 : _a.ssrTransformResult;
4513
+ if (!transformResult)
4514
+ continue;
4515
+ const sourcePos = await getOriginalPos(transformResult.map, frame);
4516
+ if (sourcePos)
4517
+ frame.sourcePos = sourcePos;
4518
+ }
4519
+ return stackFrames;
4520
+ }
4521
+ const stackIgnorePatterns = [
4522
+ "/vitest/dist/",
4523
+ "/node_modules/tinypool/",
4524
+ "/node_modules/tinyspy/"
4525
+ ];
4526
+ function parseStacktrace(e) {
4527
+ if (e.stacks)
4528
+ return e.stacks;
4529
+ const stackStr = e.stack || e.stackStr || "";
4530
+ const stackFrames = stackStr.split("\n").map((raw) => {
4512
4531
  const line = raw.trim();
4513
4532
  const match = line.match(stackFnCallRE) || line.match(stackBarePathRE);
4514
4533
  if (!match)
@@ -4516,14 +4535,17 @@ function parseStack(stack) {
4516
4535
  let file = match[2];
4517
4536
  if (file.startsWith("file://"))
4518
4537
  file = file.slice(7);
4538
+ if (stackIgnorePatterns.some((p) => file.includes(p)))
4539
+ return null;
4519
4540
  return {
4520
4541
  method: match[1],
4521
4542
  file: match[2],
4522
4543
  line: parseInt(match[3]),
4523
4544
  column: parseInt(match[4])
4524
4545
  };
4525
- });
4526
- return stackFrames.filter(notNullish);
4546
+ }).filter(notNullish);
4547
+ e.stacks = stackFrames;
4548
+ return stackFrames;
4527
4549
  }
4528
4550
  function posToNumber(source, pos) {
4529
4551
  if (typeof pos === "number")
@@ -4555,14 +4577,12 @@ async function printError(error, ctx) {
4555
4577
  stack: error
4556
4578
  };
4557
4579
  }
4558
- const stackStr = e.stack || e.stackStr || "";
4559
- const stacks = parseStack(stackStr);
4580
+ const stacks = parseStacktrace(e);
4560
4581
  if (!stacks.length) {
4561
4582
  ctx.console.error(e);
4562
4583
  } else {
4563
- const nearest = stacks.find((stack) => {
4564
- return !stack.file.includes("vitest/dist") && ctx.server.moduleGraph.getModuleById(stack.file) && existsSync(stack.file);
4565
- });
4584
+ await interpretSourcePos(stacks, ctx);
4585
+ const nearest = stacks.find((stack) => ctx.server.moduleGraph.getModuleById(stack.file) && existsSync(stack.file));
4566
4586
  printErrorMessage(e);
4567
4587
  await printStack(ctx, stacks, nearest, async (s, pos) => {
4568
4588
  if (s === nearest && nearest) {
@@ -4571,7 +4591,7 @@ async function printError(error, ctx) {
4571
4591
  }
4572
4592
  });
4573
4593
  }
4574
- handleImportOutsideModuleError(stackStr, ctx);
4594
+ handleImportOutsideModuleError(e.stack || e.stackStr || "", ctx);
4575
4595
  if (e.showDiff)
4576
4596
  displayDiff(e.actual, e.expected);
4577
4597
  }
@@ -4603,12 +4623,6 @@ As a temporary workaround you can try to inline the package by updating your con
4603
4623
  }
4604
4624
  `)));
4605
4625
  }
4606
- async function getSourcePos(ctx, nearest) {
4607
- const mod = ctx.server.moduleGraph.getModuleById(nearest.file);
4608
- const transformResult = mod == null ? void 0 : mod.ssrTransformResult;
4609
- const pos = await getOriginalPos(transformResult == null ? void 0 : transformResult.map, nearest);
4610
- return pos;
4611
- }
4612
4626
  function displayDiff(actual, expected) {
4613
4627
  console.error(c.gray(unifiedDiff(actual, expected)) + "\n");
4614
4628
  }
@@ -4620,7 +4634,7 @@ async function printStack(ctx, stack, highlight, onStack) {
4620
4634
  if (!stack.length)
4621
4635
  return;
4622
4636
  for (const frame of stack) {
4623
- const pos = await getSourcePos(ctx, frame) || frame;
4637
+ const pos = frame.sourcePos || frame;
4624
4638
  const color = frame === highlight ? c.yellow : c.gray;
4625
4639
  const path = relative(ctx.config.root, frame.file);
4626
4640
  ctx.log(color(` ${c.dim(F_POINTER)} ${[frame.method, c.dim(`${path}:${pos.line}:${pos.column}`)].filter(Boolean).join(" ")}`));
@@ -4734,4 +4748,4 @@ function formatLine(line) {
4734
4748
  return cliTruncate(line, (process.stdout.columns || 80) - 4);
4735
4749
  }
4736
4750
 
4737
- export { F_POINTER as F, F_DOWN as a, F_LONG_DASH as b, F_DOWN_RIGHT as c, F_DOT as d, F_CHECK as e, F_CROSS as f, F_RIGHT as g, stringWidth as h, ansiStyles as i, sliceAnsi as j, cliTruncate as k, getOriginalPos as l, posToNumber as m, parseStack as n, printError as p, stripAnsi as s, unifiedDiff as u };
4751
+ export { F_POINTER as F, F_DOWN as a, F_LONG_DASH as b, F_DOWN_RIGHT as c, F_DOT as d, F_CHECK as e, F_CROSS as f, F_RIGHT as g, stringWidth as h, ansiStyles as i, sliceAnsi as j, cliTruncate as k, getOriginalPos as l, posToNumber as m, parseStacktrace as n, interpretSourcePos as o, printError as p, stripAnsi as s, unifiedDiff as u };
package/dist/entry.js CHANGED
@@ -1,17 +1,17 @@
1
1
  import fs, { promises } from 'fs';
2
- import { f as format_1, h as getSerializers, p as plugins_1, b as getState, j as equals, k as iterableEquality, l as subsetEquality, m as isA, J as JestChaiExpect, n as clearContext, o as defaultSuite, q as setHooks, r as getHooks, u as context, s as setState, x as getFn, e as vi } from './vi-aef0a94d.js';
2
+ import { f as format_1, h as getSerializers, p as plugins_1, j as equals, b as getState, k as iterableEquality, l as subsetEquality, m as isA, J as JestChaiExpect, n as clearContext, o as defaultSuite, q as setHooks, r as getHooks, u as context, s as setState, x as getFn, e as vi } from './vi-02a9c349.js';
3
3
  import { Console } from 'console';
4
4
  import { Writable } from 'stream';
5
5
  import { importModule } from 'local-pkg';
6
6
  import chai$1, { expect, util } from 'chai';
7
7
  import { a as commonjsRequire, c as commonjsGlobal } from './_commonjsHelpers-c9e3b764.js';
8
- import { u as index, s as slash, v as getNames, c, t as toArray, r as relative, w as partitionSuiteChildren, x as hasTests, h as hasFailed } from './index-250bdca0.js';
8
+ import { u as index, s as slash, v as getNames, c, t as toArray, r as relative, w as partitionSuiteChildren, x as hasTests, h as hasFailed } from './index-f0488a5d.js';
9
9
  import { r as rpc } from './rpc-8c7cc374.js';
10
- import { l as getOriginalPos, m as posToNumber, n as parseStack, u as unifiedDiff } from './diff-a0cbb825.js';
10
+ import { l as getOriginalPos, m as posToNumber, n as parseStacktrace, u as unifiedDiff } from './diff-711cddf1.js';
11
11
  import { performance as performance$1 } from 'perf_hooks';
12
12
  import { createHash } from 'crypto';
13
13
  import { format } from 'util';
14
- import './jest-mock-038a01b3.js';
14
+ import './jest-mock-30625866.js';
15
15
  import 'tinyspy';
16
16
  import 'url';
17
17
  import 'tty';
@@ -589,7 +589,6 @@ class SnapshotState {
589
589
  this._inlineSnapshots = [];
590
590
  this._uncheckedKeys = new Set(Object.keys(this._snapshotData));
591
591
  this._counters = new Map();
592
- this._index = 0;
593
592
  this.expand = options.expand || false;
594
593
  this.added = 0;
595
594
  this.matched = 0;
@@ -610,7 +609,7 @@ class SnapshotState {
610
609
  this._dirty = true;
611
610
  if (options.isInline) {
612
611
  const error = options.error || new Error("Unknown error");
613
- const stacks = parseStack(error.stack || "");
612
+ const stacks = parseStacktrace(error);
614
613
  stacks.forEach((i) => i.file = slash(i.file));
615
614
  const stack = stacks.find((i) => process.__vitest_worker__.ctx.files.includes(i.file));
616
615
  if (!stack) {
@@ -626,7 +625,6 @@ class SnapshotState {
626
625
  clear() {
627
626
  this._snapshotData = this._initialData;
628
627
  this._counters = new Map();
629
- this._index = 0;
630
628
  this.added = 0;
631
629
  this.matched = 0;
632
630
  this.unmatched = 0;
@@ -987,12 +985,11 @@ const getMatcherState = (assertion) => {
987
985
  iterableEquality,
988
986
  subsetEquality
989
987
  });
990
- const matcherState = __spreadProps(__spreadValues({
988
+ const matcherState = __spreadProps(__spreadValues({}, getState()), {
991
989
  isNot,
992
990
  utils: jestUtils,
993
991
  promise,
994
- equals
995
- }, getState()), {
992
+ equals,
996
993
  suppressedErrors: []
997
994
  });
998
995
  return {
@@ -1228,7 +1225,7 @@ async function setupGlobalEnv(config) {
1228
1225
  setupConsoleLogSpy();
1229
1226
  await setupChai();
1230
1227
  if (config.global)
1231
- (await import('./global-f9288768.js')).registerApiGlobally();
1228
+ (await import('./global-60f865bb.js')).registerApiGlobally();
1232
1229
  }
1233
1230
  function setupConsoleLogSpy() {
1234
1231
  const stdout = new Writable({
@@ -1276,7 +1273,8 @@ async function runSetupFiles(config) {
1276
1273
  }));
1277
1274
  }
1278
1275
 
1279
- function serializeError(val, seen = new WeakSet()) {
1276
+ const OBJECT_PROTO = Object.getPrototypeOf({});
1277
+ function serializeError(val, seen = new WeakMap()) {
1280
1278
  if (!val || typeof val === "string")
1281
1279
  return val;
1282
1280
  if (typeof val === "function")
@@ -1290,18 +1288,27 @@ function serializeError(val, seen = new WeakSet()) {
1290
1288
  if (typeof val.asymmetricMatch === "function")
1291
1289
  return `${val.toString()} ${format(val.sample)}`;
1292
1290
  if (seen.has(val))
1293
- return val;
1294
- seen.add(val);
1291
+ return seen.get(val);
1295
1292
  if (Array.isArray(val)) {
1296
- val = val.map((e) => {
1297
- return serializeError(e, seen);
1293
+ const clone = new Array(val.length);
1294
+ seen.set(val, clone);
1295
+ val.forEach((e, i) => {
1296
+ clone[i] = serializeError(e, seen);
1298
1297
  });
1298
+ return clone;
1299
1299
  } else {
1300
- Object.keys(val).forEach((key) => {
1301
- val[key] = serializeError(val[key], seen);
1302
- });
1300
+ const clone = Object.create(null);
1301
+ seen.set(val, clone);
1302
+ let obj = val;
1303
+ while (obj && obj !== OBJECT_PROTO) {
1304
+ Object.getOwnPropertyNames(obj).forEach((key) => {
1305
+ if (!(key in clone))
1306
+ clone[key] = serializeError(obj[key], seen);
1307
+ });
1308
+ obj = Object.getPrototypeOf(obj);
1309
+ }
1310
+ return clone;
1303
1311
  }
1304
- return val;
1305
1312
  }
1306
1313
  function processError(err) {
1307
1314
  if (!err)
@@ -1310,9 +1317,9 @@ function processError(err) {
1310
1317
  err.stackStr = String(err.stack);
1311
1318
  if (err.name)
1312
1319
  err.nameStr = String(err.name);
1313
- if (typeof err.expected !== "string")
1320
+ if (err.expected && typeof err.expected !== "string")
1314
1321
  err.expected = stringify(err.expected);
1315
- if (typeof err.actual !== "string")
1322
+ if (err.actual && typeof err.actual !== "string")
1316
1323
  err.actual = stringify(err.actual);
1317
1324
  return serializeError(err);
1318
1325
  }
@@ -1320,9 +1327,6 @@ function processError(err) {
1320
1327
  function hash(str, length = 10) {
1321
1328
  return createHash("md5").update(str).digest("hex").slice(0, length);
1322
1329
  }
1323
- function inModuleGraph(files) {
1324
- return files.some((file) => process.__vitest_worker__.moduleCache.has(file));
1325
- }
1326
1330
  async function collectTests(paths, config) {
1327
1331
  const files = [];
1328
1332
  for (const filepath of paths) {
@@ -1339,8 +1343,6 @@ async function collectTests(paths, config) {
1339
1343
  try {
1340
1344
  await runSetupFiles(config);
1341
1345
  await import(filepath);
1342
- if (config.findRelatedTests && !inModuleGraph(config.findRelatedTests))
1343
- continue;
1344
1346
  const defaultTasks = await defaultSuite.collect(file);
1345
1347
  setHooks(file, getHooks(defaultTasks));
1346
1348
  for (const c of [...defaultTasks.tasks, ...context.tasks]) {
@@ -1424,11 +1426,11 @@ async function callSuiteHook(suite, name, args) {
1424
1426
  if (name === "afterEach" && suite.suite)
1425
1427
  await callSuiteHook(suite.suite, name, args);
1426
1428
  }
1427
- const packs = [];
1429
+ const packs = new Map();
1428
1430
  let updateTimer;
1429
1431
  let previousUpdate;
1430
1432
  function updateTask(task) {
1431
- packs.push([task.id, task.result]);
1433
+ packs.set(task.id, task.result);
1432
1434
  clearTimeout(updateTimer);
1433
1435
  updateTimer = setTimeout(() => {
1434
1436
  previousUpdate = sendTasksUpdate();
@@ -1437,9 +1439,9 @@ function updateTask(task) {
1437
1439
  async function sendTasksUpdate() {
1438
1440
  clearTimeout(updateTimer);
1439
1441
  await previousUpdate;
1440
- if (packs.length) {
1441
- const p = rpc().onTaskUpdate(packs);
1442
- packs.length = 0;
1442
+ if (packs.size) {
1443
+ const p = rpc().onTaskUpdate(Array.from(packs));
1444
+ packs.clear();
1443
1445
  return p;
1444
1446
  }
1445
1447
  }
@@ -1,15 +1,15 @@
1
- import { g as globalApis } from './constants-744cb76d.js';
2
- import { i as index } from './index-68c0c743.js';
1
+ import { g as globalApis } from './constants-2cd49e0a.js';
2
+ import { i as index } from './index-de2249ec.js';
3
3
  import 'url';
4
- import './index-250bdca0.js';
4
+ import './index-f0488a5d.js';
5
5
  import 'tty';
6
6
  import 'local-pkg';
7
7
  import 'path';
8
- import './vi-aef0a94d.js';
9
- import './_commonjsHelpers-c9e3b764.js';
10
- import './jest-mock-038a01b3.js';
8
+ import './vi-02a9c349.js';
9
+ import './jest-mock-30625866.js';
11
10
  import 'chai';
12
11
  import 'tinyspy';
12
+ import './_commonjsHelpers-c9e3b764.js';
13
13
 
14
14
  function registerApiGlobally() {
15
15
  globalApis.forEach((api) => {
@@ -1,17 +1,17 @@
1
- import { c, s as slash$1, a as isAbsolute, r as relative, d as dirname, b as basename, g as getFullName, h as hasFailed, f as getSuites, j as getTests, t as toArray, k as resolve, l as deepMerge, m as toFilePath, n as noop$1, e as ensurePackageInstalled } from './index-250bdca0.js';
1
+ import fs$8, { promises, existsSync } from 'fs';
2
+ import { c, s as slash$1, a as isAbsolute, r as relative, d as dirname, b as basename, g as getFullName, h as hasFailed, f as getSuites, j as getTests, t as toArray, k as resolve, l as deepMerge, m as toFilePath, n as noop$1, e as ensurePackageInstalled } from './index-f0488a5d.js';
2
3
  import { createServer, mergeConfig } from 'vite';
3
4
  import path$a from 'path';
4
5
  import process$1 from 'process';
5
- import fs$8, { promises, existsSync } from 'fs';
6
6
  import require$$0 from 'os';
7
7
  import require$$0$1 from 'util';
8
8
  import require$$0$2 from 'stream';
9
9
  import require$$2 from 'events';
10
- import { d as defaultInclude, a as defaultExclude, b as defaultPort, c as distDir, e as configFiles } from './constants-744cb76d.js';
10
+ import { d as defaultInclude, a as defaultExclude, b as defaultPort, c as distDir, e as configFiles } from './constants-2cd49e0a.js';
11
11
  import MagicString from './magic-string.es-94000aea.js';
12
12
  import { performance } from 'perf_hooks';
13
- import { F as F_POINTER, a as F_DOWN, s as stripAnsi, b as F_LONG_DASH, c as F_DOWN_RIGHT, d as F_DOT, e as F_CHECK, f as F_CROSS, g as F_RIGHT, p as printError, h as stringWidth, i as ansiStyles, j as sliceAnsi, k as cliTruncate } from './diff-a0cbb825.js';
14
- import { o as onetime, s as signalExit } from './index-648e7ab2.js';
13
+ import { F as F_POINTER, a as F_DOWN, s as stripAnsi, b as F_LONG_DASH, c as F_DOWN_RIGHT, d as F_DOT, e as F_CHECK, f as F_CROSS, g as F_RIGHT, p as printError, h as stringWidth, i as ansiStyles, j as sliceAnsi, k as cliTruncate } from './diff-711cddf1.js';
14
+ import { o as onetime, s as signalExit } from './index-7975be53.js';
15
15
  import { createRequire } from 'module';
16
16
  import { pathToFileURL } from 'url';
17
17
  import { MessageChannel } from 'worker_threads';
@@ -7597,7 +7597,6 @@ createLogUpdate(process$1.stdout);
7597
7597
  createLogUpdate(process$1.stderr);
7598
7598
 
7599
7599
  const DURATION_LONG = 300;
7600
- const MAX_HEIGHT = 20;
7601
7600
  const outputMap = new WeakMap();
7602
7601
  function formatFilepath(path) {
7603
7602
  const lastSlash = Math.max(path.lastIndexOf("/") + 1, 0);
@@ -7643,7 +7642,7 @@ function renderTree(tasks, options, level = 0) {
7643
7642
  output = output.concat(renderTree(task.tasks, options, level + 1));
7644
7643
  }
7645
7644
  }
7646
- return output.slice(0, MAX_HEIGHT).join("\n");
7645
+ return output.join("\n");
7647
7646
  }
7648
7647
  const createListRenderer = (_tasks, options) => {
7649
7648
  let tasks = _tasks;
@@ -7980,8 +7979,8 @@ function resolveConfig(options, viteConfig) {
7980
7979
  resolved.setupFiles = Array.from(resolved.setupFiles || []).map((i) => resolve(resolved.root, i));
7981
7980
  if (resolved.api === true)
7982
7981
  resolved.api = defaultPort;
7983
- if (options.findRelatedTests)
7984
- resolved.findRelatedTests = toArray(options.findRelatedTests).map((file) => resolve(resolved.root, file));
7982
+ if (options.related)
7983
+ resolved.related = toArray(options.related).map((file) => resolve(resolved.root, file));
7985
7984
  return resolved;
7986
7985
  }
7987
7986
 
@@ -8188,7 +8187,7 @@ class Vitest {
8188
8187
  }
8189
8188
  async start(filters) {
8190
8189
  this.report("onInit", this);
8191
- const files = await this.globTestFiles(filters);
8190
+ const files = await this.filterTestsBySource(await this.globTestFiles(filters));
8192
8191
  if (!files.length) {
8193
8192
  if (this.config.passWithNoTests)
8194
8193
  this.log("No test files found\n");
@@ -8202,6 +8201,42 @@ class Vitest {
8202
8201
  if (this.config.coverage.enabled)
8203
8202
  await reportCoverage(this);
8204
8203
  }
8204
+ async getTestDependencies(filepath) {
8205
+ const deps = new Set();
8206
+ const addImports = async (filepath2) => {
8207
+ const transformed = await this.server.transformRequest(filepath2, { ssr: true });
8208
+ if (!transformed)
8209
+ return;
8210
+ const dependencies = [...transformed.deps || [], ...transformed.dynamicDeps || []];
8211
+ for (const dep of dependencies) {
8212
+ const path = await this.server.pluginContainer.resolveId(dep, filepath2, { ssr: true });
8213
+ const fsPath = path && !path.external && path.id.split("?")[0];
8214
+ if (fsPath && !fsPath.includes("node_modules") && !deps.has(fsPath) && existsSync(fsPath)) {
8215
+ deps.add(fsPath);
8216
+ await addImports(fsPath);
8217
+ }
8218
+ }
8219
+ };
8220
+ await addImports(filepath);
8221
+ return deps;
8222
+ }
8223
+ async filterTestsBySource(tests) {
8224
+ const related = this.config.related;
8225
+ if (!related)
8226
+ return tests;
8227
+ if (!related.length)
8228
+ return [];
8229
+ const testDeps = await Promise.all(tests.map(async (filepath) => {
8230
+ const deps = await this.getTestDependencies(filepath);
8231
+ return [filepath, deps];
8232
+ }));
8233
+ const runningTests = [];
8234
+ for (const [filepath, deps] of testDeps) {
8235
+ if (deps.size && related.some((path) => deps.has(path)))
8236
+ runningTests.push(filepath);
8237
+ }
8238
+ return runningTests;
8239
+ }
8205
8240
  async runFiles(files) {
8206
8241
  await this.runningPromise;
8207
8242
  this.runningPromise = (async () => {
@@ -8365,7 +8400,7 @@ async function createVitest(options, viteOverrides = {}) {
8365
8400
  await ctx.setServer(options, server2);
8366
8401
  haveStarted = true;
8367
8402
  if (options.api)
8368
- (await import('./setup-647e44ef.js')).setup(ctx);
8403
+ (await import('./setup-3d1395ff.js')).setup(ctx);
8369
8404
  }
8370
8405
  },
8371
8406
  MocksPlugin(),
@@ -8378,18 +8413,13 @@ async function createVitest(options, viteOverrides = {}) {
8378
8413
  },
8379
8414
  build: {
8380
8415
  sourcemap: true
8381
- },
8382
- optimizeDeps: {
8383
- exclude: [
8384
- "vitest"
8385
- ]
8386
8416
  }
8387
8417
  };
8388
8418
  const server = await createServer(mergeConfig(config, viteOverrides));
8389
8419
  await server.pluginContainer.buildStart({});
8390
8420
  if (options.api === true)
8391
8421
  options.api = defaultPort;
8392
- if (options.open && !options.api)
8422
+ if (options.open && typeof options.api !== "number")
8393
8423
  options.api = defaultPort;
8394
8424
  if (typeof options.api === "number")
8395
8425
  await server.listen(options.api);
@@ -2,8 +2,8 @@ import path$2 from 'path';
2
2
  import fs$2 from 'fs';
3
3
  import require$$0 from 'util';
4
4
  import childProcess$1 from 'child_process';
5
- import { p as pathKey, m as mergeStream$1, a as getStream$1, b as crossSpawn$1 } from './index-6e709f57.js';
6
- import { a as signalExit, b as onetime$1 } from './index-648e7ab2.js';
5
+ import { p as pathKey, m as mergeStream$1, a as getStream$1, b as crossSpawn$1 } from './index-4cd25949.js';
6
+ import { a as signalExit, b as onetime$1 } from './index-7975be53.js';
7
7
  import require$$0$1 from 'os';
8
8
  import './_commonjsHelpers-c9e3b764.js';
9
9
  import 'buffer';
File without changes
File without changes
@@ -1,6 +1,6 @@
1
- import { g as getCurrentSuite, w as withTimeout, a as getDefaultHookTimeout, b as getState, s as setState, c as suite, t as test, d as describe, i as it, v as vitest, e as vi } from './vi-aef0a94d.js';
1
+ import { g as getCurrentSuite, w as withTimeout, a as getDefaultHookTimeout, b as getState, s as setState, c as suite, t as test, d as describe, i as it, v as vitest, e as vi } from './vi-02a9c349.js';
2
2
  import chai, { assert, should } from 'chai';
3
- import { s as spies, a as spyOn, f as fn } from './jest-mock-038a01b3.js';
3
+ import { s as spies, i as isMockFunction, a as spyOn, f as fn } from './jest-mock-30625866.js';
4
4
 
5
5
  const beforeAll = (fn, timeout) => getCurrentSuite().on("beforeAll", withTimeout(fn, timeout ?? getDefaultHookTimeout()));
6
6
  const afterAll = (fn, timeout) => getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout()));
@@ -29,6 +29,7 @@ var index = /*#__PURE__*/Object.freeze({
29
29
  chai: chai,
30
30
  expect: expect,
31
31
  spies: spies,
32
+ isMockFunction: isMockFunction,
32
33
  spyOn: spyOn,
33
34
  fn: fn,
34
35
  vitest: vitest,
@@ -249,13 +249,6 @@ const index = {
249
249
  ..._path
250
250
  };
251
251
 
252
- const isWindows = process.platform === "win32";
253
- function toArray(array) {
254
- array = array || [];
255
- if (Array.isArray(array))
256
- return array;
257
- return [array];
258
- }
259
252
  function notNullish(v) {
260
253
  return v != null;
261
254
  }
@@ -267,29 +260,20 @@ function mergeSlashes(str) {
267
260
  }
268
261
  const noop = () => {
269
262
  };
270
- function partitionSuiteChildren(suite) {
271
- let tasksGroup = [];
272
- const tasksGroups = [];
273
- for (const c2 of suite.tasks) {
274
- if (tasksGroup.length === 0 || c2.concurrent === tasksGroup[0].concurrent) {
275
- tasksGroup.push(c2);
276
- } else {
277
- tasksGroups.push(tasksGroup);
278
- tasksGroup = [c2];
279
- }
280
- }
281
- if (tasksGroup.length > 0)
282
- tasksGroups.push(tasksGroup);
283
- return tasksGroups;
263
+ function toArray(array) {
264
+ array = array || [];
265
+ if (Array.isArray(array))
266
+ return array;
267
+ return [array];
284
268
  }
285
269
  function getTests(suite) {
286
- return toArray(suite).flatMap((s) => s.type === "test" ? [s] : s.tasks.flatMap((c2) => c2.type === "test" ? [c2] : getTests(c2)));
270
+ return toArray(suite).flatMap((s) => s.type === "test" ? [s] : s.tasks.flatMap((c) => c.type === "test" ? [c] : getTests(c)));
287
271
  }
288
272
  function getSuites(suite) {
289
273
  return toArray(suite).flatMap((s) => s.type === "suite" ? [s, ...getSuites(s.tasks)] : []);
290
274
  }
291
275
  function hasTests(suite) {
292
- return toArray(suite).some((s) => s.tasks.some((c2) => c2.type === "test" || hasTests(c2)));
276
+ return toArray(suite).some((s) => s.tasks.some((c) => c.type === "test" || hasTests(c)));
293
277
  }
294
278
  function hasFailed(suite) {
295
279
  return toArray(suite).some((s) => {
@@ -307,6 +291,23 @@ function getNames(task) {
307
291
  }
308
292
  return names;
309
293
  }
294
+
295
+ const isWindows = process.platform === "win32";
296
+ function partitionSuiteChildren(suite) {
297
+ let tasksGroup = [];
298
+ const tasksGroups = [];
299
+ for (const c2 of suite.tasks) {
300
+ if (tasksGroup.length === 0 || c2.concurrent === tasksGroup[0].concurrent) {
301
+ tasksGroup.push(c2);
302
+ } else {
303
+ tasksGroups.push(tasksGroup);
304
+ tasksGroup = [c2];
305
+ }
306
+ }
307
+ if (tasksGroup.length > 0)
308
+ tasksGroups.push(tasksGroup);
309
+ return tasksGroups;
310
+ }
310
311
  function getFullName(task) {
311
312
  return getNames(task).join(c.dim(" > "));
312
313
  }
@@ -325,7 +326,7 @@ async function ensurePackageInstalled(dependency, promptInstall = !process.env.C
325
326
  message: c.reset(`Do you want to install ${c.green(dependency)}?`)
326
327
  });
327
328
  if (install) {
328
- await (await import('./index-ce49e384.js')).installPackage(dependency, { dev: true });
329
+ await (await import('./index-26cb6e63.js')).installPackage(dependency, { dev: true });
329
330
  return true;
330
331
  }
331
332
  return false;
package/dist/index.d.ts CHANGED
@@ -212,6 +212,8 @@ declare class Vitest {
212
212
  constructor();
213
213
  setServer(options: UserConfig, server: ViteDevServer): Promise<void>;
214
214
  start(filters?: string[]): Promise<void>;
215
+ private getTestDependencies;
216
+ filterTestsBySource(tests: string[]): Promise<string[]>;
215
217
  runFiles(files: string[]): Promise<void>;
216
218
  log(...args: any[]): void;
217
219
  error(...args: any[]): void;
@@ -369,6 +371,18 @@ interface ParsedStack {
369
371
  file: string;
370
372
  line: number;
371
373
  column: number;
374
+ sourcePos?: Position;
375
+ }
376
+ interface ErrorWithDiff extends Error {
377
+ name: string;
378
+ nameStr?: string;
379
+ stack?: string;
380
+ stackStr?: string;
381
+ stacks?: ParsedStack[];
382
+ showDiff?: boolean;
383
+ actual?: any;
384
+ expected?: any;
385
+ operator?: string;
372
386
  }
373
387
 
374
388
  declare type ChainableFunction<T extends string, Args extends any[], R = any> = {
@@ -391,7 +405,7 @@ interface TaskBase {
391
405
  interface TaskResult {
392
406
  state: TaskState;
393
407
  duration?: number;
394
- error?: unknown;
408
+ error?: ErrorWithDiff;
395
409
  }
396
410
  declare type TaskResultPack = [id: string, result: TaskResult | undefined];
397
411
  interface Suite extends TaskBase {
@@ -693,13 +707,13 @@ interface UserConfig extends InlineConfig {
693
707
  /**
694
708
  * Run tests that cover a list of source files
695
709
  */
696
- findRelatedTests?: string[] | string;
710
+ related?: string[] | string;
697
711
  }
698
- interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'findRelatedTests'> {
712
+ interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'related'> {
699
713
  config?: string;
700
714
  filters?: string[];
701
715
  testNamePattern?: RegExp;
702
- findRelatedTests?: string[];
716
+ related?: string[];
703
717
  depsInline: (string | RegExp)[];
704
718
  depsExternal: (string | RegExp)[];
705
719
  fallbackCJS: boolean;
@@ -808,6 +822,7 @@ interface MockWithArgs<T extends MockableFunction> extends JestMockCompatFn<Argu
808
822
  (...args: ArgumentsOf<T>): ReturnType<T>;
809
823
  }
810
824
  declare const spies: Set<JestMockCompat<any[], any>>;
825
+ declare function isMockFunction(fn: any): fn is EnhancedSpy;
811
826
  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;
812
827
  declare type Awaited<T> = T extends Promise<infer R> ? R : never;
813
828
  declare function fn<TArgs extends any[] = any[], R = any>(): JestMockCompatFn<TArgs, R>;
@@ -885,7 +900,7 @@ declare class VitestUtils {
885
900
  */
886
901
  mocked<T>(item: T, deep?: false): MaybeMocked<T>;
887
902
  mocked<T>(item: T, deep: true): MaybeMockedDeep<T>;
888
- isMockFunction(fn: any): any;
903
+ isMockFunction(fn: any): fn is EnhancedSpy;
889
904
  clearAllMocks(): this;
890
905
  resetAllMocks(): this;
891
906
  restoreAllMocks(): this;
@@ -896,7 +911,8 @@ declare const vi: VitestUtils;
896
911
  interface WebSocketHandlers {
897
912
  getFiles(): File[];
898
913
  getConfig(): ResolvedConfig;
899
- getSourceCode(id: string): Promise<string>;
914
+ readFile(id: string): Promise<string>;
915
+ writeFile(id: string, content: string): Promise<void>;
900
916
  getModuleGraph(id: string): Promise<{
901
917
  graph: Record<string, string[]>;
902
918
  externalized: string[];
@@ -996,4 +1012,4 @@ declare global {
996
1012
  }
997
1013
  }
998
1014
 
999
- export { ArgumentsOf, ArgumentsType, Arrayable, Awaitable, BuiltinEnvironment, ConstructorArgumentsOf, DoneCallback, EnhancedSpy, Environment, EnvironmentReturn, File, HookListener, InlineConfig, JestMockCompat, JestMockCompatContext, JestMockCompatFn, MaybeMocked, MaybeMockedConstructor, MaybeMockedDeep, MethodKeysOf, MockWithArgs, MockableFunction, MockedFunction, MockedFunctionDeep, MockedObject, MockedObjectDeep, ModuleCache, Nullable, ParsedStack, Position, PropertyKeysOf, Reporter, ResolvedConfig, RunMode, RuntimeContext, SnapshotData, SnapshotMatchOptions, SnapshotResult, SnapshotStateOptions, SnapshotSummary, SnapshotUpdateState, Suite, SuiteCollector, SuiteHooks, Task, TaskBase, TaskResult, TaskResultPack, TaskState, Test, TestCollector, TestFactory, TestFunction, UncheckedSnapshot, UserConfig, UserConsoleLog, WebSocketEvents, WebSocketHandlers, WorkerContext, WorkerRPC, afterAll, afterEach, beforeAll, beforeEach, describe, expect, fn, it, spies, spyOn, suite, test, vi, vitest };
1015
+ export { ArgumentsOf, ArgumentsType, Arrayable, Awaitable, BuiltinEnvironment, ConstructorArgumentsOf, DoneCallback, EnhancedSpy, Environment, EnvironmentReturn, ErrorWithDiff, File, HookListener, InlineConfig, JestMockCompat, JestMockCompatContext, JestMockCompatFn, MaybeMocked, MaybeMockedConstructor, MaybeMockedDeep, MethodKeysOf, MockWithArgs, MockableFunction, MockedFunction, MockedFunctionDeep, MockedObject, MockedObjectDeep, ModuleCache, Nullable, ParsedStack, Position, PropertyKeysOf, Reporter, ResolvedConfig, RunMode, RuntimeContext, SnapshotData, SnapshotMatchOptions, SnapshotResult, SnapshotStateOptions, SnapshotSummary, SnapshotUpdateState, Suite, SuiteCollector, SuiteHooks, Task, TaskBase, TaskResult, TaskResultPack, TaskState, Test, TestCollector, TestFactory, TestFunction, UncheckedSnapshot, UserConfig, UserConsoleLog, WebSocketEvents, WebSocketHandlers, WorkerContext, WorkerRPC, afterAll, afterEach, beforeAll, beforeEach, describe, expect, fn, isMockFunction, it, spies, spyOn, suite, test, vi, vitest };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- export { d as describe, i as it, c as suite, t as test, e as vi, v as vitest } from './vi-aef0a94d.js';
2
- export { a as afterAll, d as afterEach, b as beforeAll, c as beforeEach, e as expect } from './index-68c0c743.js';
3
- export { f as fn, s as spies, a as spyOn } from './jest-mock-038a01b3.js';
1
+ export { d as describe, i as it, c as suite, t as test, e as vi, v as vitest } from './vi-02a9c349.js';
2
+ export { a as afterAll, d as afterEach, b as beforeAll, c as beforeEach, e as expect } from './index-de2249ec.js';
3
+ export { f as fn, i as isMockFunction, s as spies, a as spyOn } from './jest-mock-30625866.js';
4
4
  export { assert, default as chai, should } from 'chai';
5
- import './index-250bdca0.js';
5
+ import './index-f0488a5d.js';
6
6
  import 'url';
7
7
  import 'tty';
8
8
  import 'local-pkg';
@@ -2,6 +2,9 @@ import { util } from 'chai';
2
2
  import * as tinyspy from 'tinyspy';
3
3
 
4
4
  const spies = new Set();
5
+ function isMockFunction(fn2) {
6
+ return typeof fn2 === "function" && "__isSpy" in fn2 && fn2.__isSpy;
7
+ }
5
8
  function spyOn(obj, method, accessType) {
6
9
  const dictionary = {
7
10
  get: "getter",
@@ -87,4 +90,4 @@ function fn(implementation) {
87
90
  }) }, "fn"));
88
91
  }
89
92
 
90
- export { spyOn as a, fn as f, spies as s };
93
+ export { spyOn as a, fn as f, isMockFunction as i, spies as s };
package/dist/node.d.ts CHANGED
@@ -122,6 +122,28 @@ interface UserConsoleLog {
122
122
  type: 'stdout' | 'stderr';
123
123
  taskId?: string;
124
124
  }
125
+ interface Position {
126
+ line: number;
127
+ column: number;
128
+ }
129
+ interface ParsedStack {
130
+ method: string;
131
+ file: string;
132
+ line: number;
133
+ column: number;
134
+ sourcePos?: Position;
135
+ }
136
+ interface ErrorWithDiff extends Error {
137
+ name: string;
138
+ nameStr?: string;
139
+ stack?: string;
140
+ stackStr?: string;
141
+ stacks?: ParsedStack[];
142
+ showDiff?: boolean;
143
+ actual?: any;
144
+ expected?: any;
145
+ operator?: string;
146
+ }
125
147
 
126
148
  declare type RunMode = 'run' | 'skip' | 'only' | 'todo';
127
149
  declare type TaskState = RunMode | 'pass' | 'fail';
@@ -137,7 +159,7 @@ interface TaskBase {
137
159
  interface TaskResult {
138
160
  state: TaskState;
139
161
  duration?: number;
140
- error?: unknown;
162
+ error?: ErrorWithDiff;
141
163
  }
142
164
  declare type TaskResultPack = [id: string, result: TaskResult | undefined];
143
165
  interface Suite extends TaskBase {
@@ -401,13 +423,13 @@ interface UserConfig extends InlineConfig {
401
423
  /**
402
424
  * Run tests that cover a list of source files
403
425
  */
404
- findRelatedTests?: string[] | string;
426
+ related?: string[] | string;
405
427
  }
406
- interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'findRelatedTests'> {
428
+ interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'related'> {
407
429
  config?: string;
408
430
  filters?: string[];
409
431
  testNamePattern?: RegExp;
410
- findRelatedTests?: string[];
432
+ related?: string[];
411
433
  depsInline: (string | RegExp)[];
412
434
  depsExternal: (string | RegExp)[];
413
435
  fallbackCJS: boolean;
@@ -466,6 +488,8 @@ declare class Vitest {
466
488
  constructor();
467
489
  setServer(options: UserConfig, server: ViteDevServer): Promise<void>;
468
490
  start(filters?: string[]): Promise<void>;
491
+ private getTestDependencies;
492
+ filterTestsBySource(tests: string[]): Promise<string[]>;
469
493
  runFiles(files: string[]): Promise<void>;
470
494
  log(...args: any[]): void;
471
495
  error(...args: any[]): void;
package/dist/node.js CHANGED
@@ -1,21 +1,21 @@
1
- export { c as createVitest } from './index-a7ae9662.js';
2
- import './index-250bdca0.js';
1
+ export { c as createVitest } from './index-05648ba5.js';
2
+ import 'fs';
3
+ import './index-f0488a5d.js';
3
4
  import 'url';
4
5
  import 'tty';
5
6
  import 'local-pkg';
6
7
  import 'path';
7
8
  import 'vite';
8
9
  import 'process';
9
- import 'fs';
10
10
  import 'os';
11
11
  import 'util';
12
12
  import 'stream';
13
13
  import 'events';
14
- import './constants-744cb76d.js';
14
+ import './constants-2cd49e0a.js';
15
15
  import './magic-string.es-94000aea.js';
16
16
  import 'perf_hooks';
17
- import './diff-a0cbb825.js';
18
- import './index-648e7ab2.js';
17
+ import './diff-711cddf1.js';
18
+ import './index-7975be53.js';
19
19
  import './_commonjsHelpers-c9e3b764.js';
20
20
  import 'assert';
21
21
  import 'module';
@@ -9,9 +9,10 @@ import require$$2 from 'events';
9
9
  import require$$1 from 'https';
10
10
  import require$$2$1 from 'http';
11
11
  import require$$7 from 'url';
12
- import { A as API_PATH } from './constants-744cb76d.js';
12
+ import { A as API_PATH } from './constants-2cd49e0a.js';
13
13
  import { s as shouldExternalize } from './externalize-2f63779d.js';
14
- import './index-250bdca0.js';
14
+ import { o as interpretSourcePos, n as parseStacktrace } from './diff-711cddf1.js';
15
+ import './index-f0488a5d.js';
15
16
  import 'tty';
16
17
  import 'local-pkg';
17
18
  import 'path';
@@ -4270,9 +4271,12 @@ function setup(ctx) {
4270
4271
  getFiles() {
4271
4272
  return ctx.state.getFiles();
4272
4273
  },
4273
- getSourceCode(id) {
4274
+ readFile(id) {
4274
4275
  return promises.readFile(id, "utf-8");
4275
4276
  },
4277
+ writeFile(id, content) {
4278
+ return promises.writeFile(id, content, "utf-8");
4279
+ },
4276
4280
  async rerun(files) {
4277
4281
  await ctx.report("onWatcherRerun", files);
4278
4282
  await ctx.runFiles(files);
@@ -4335,12 +4339,21 @@ class WebSocketReporter {
4335
4339
  this.clients = clients;
4336
4340
  }
4337
4341
  onCollected(files) {
4342
+ if (this.clients.size === 0)
4343
+ return;
4338
4344
  this.clients.forEach((client) => {
4339
4345
  var _a;
4340
4346
  (_a = client.onCollected) == null ? void 0 : _a.call(client, files);
4341
4347
  });
4342
4348
  }
4343
- onTaskUpdate(packs) {
4349
+ async onTaskUpdate(packs) {
4350
+ if (this.clients.size === 0)
4351
+ return;
4352
+ await Promise.all(packs.map(async (i) => {
4353
+ var _a;
4354
+ if ((_a = i[1]) == null ? void 0 : _a.error)
4355
+ await interpretSourcePos(parseStacktrace(i[1].error), this.ctx);
4356
+ }));
4344
4357
  this.clients.forEach((client) => {
4345
4358
  var _a;
4346
4359
  (_a = client.onTaskUpdate) == null ? void 0 : _a.call(client, packs);
@@ -1,6 +1,6 @@
1
- import { n as noop, i as isObject } from './index-250bdca0.js';
1
+ import { n as noop, i as isObject } from './index-f0488a5d.js';
2
+ import { i as isMockFunction, a as spyOn, f as fn, s as spies } from './jest-mock-30625866.js';
2
3
  import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './_commonjsHelpers-c9e3b764.js';
3
- import { a as spyOn, f as fn, s as spies } from './jest-mock-038a01b3.js';
4
4
 
5
5
  var __defProp = Object.defineProperty;
6
6
  var __defProps = Object.defineProperties;
@@ -2808,6 +2808,20 @@ const JestChaiExpect = (chai, utils) => {
2808
2808
  def("chaiEqual", function(...args) {
2809
2809
  return chaiEqual.apply(this, args);
2810
2810
  });
2811
+ ["throw", "throws", "Throw"].forEach((m) => {
2812
+ utils.overwriteMethod(chai.Assertion.prototype, m, (_super) => {
2813
+ return function(...args) {
2814
+ const promise = utils.flag(this, "promise");
2815
+ const object = utils.flag(this, "object");
2816
+ if (promise === "rejects") {
2817
+ utils.flag(this, "object", () => {
2818
+ throw object;
2819
+ });
2820
+ }
2821
+ _super.apply(this, args);
2822
+ };
2823
+ });
2824
+ });
2811
2825
  utils.overwriteMethod(chai.Assertion.prototype, "equal", (_super) => {
2812
2826
  return function(...args) {
2813
2827
  const expected = args[0];
@@ -2861,12 +2875,7 @@ const JestChaiExpect = (chai, utils) => {
2861
2875
  def("toContainEqual", function(expected) {
2862
2876
  const obj = utils.flag(this, "object");
2863
2877
  const index = Array.from(obj).findIndex((item) => {
2864
- try {
2865
- chai.assert.deepEqual(item, expected);
2866
- } catch {
2867
- return false;
2868
- }
2869
- return true;
2878
+ return equals(item, expected);
2870
2879
  });
2871
2880
  this.assert(index !== -1, "expected #{this} to deep equally contain #{exp}", "expected #{this} to not deep equally contain #{exp}", expected);
2872
2881
  });
@@ -2915,15 +2924,24 @@ const JestChaiExpect = (chai, utils) => {
2915
2924
  def("toHaveProperty", function(...args) {
2916
2925
  return this.have.deep.nested.property(...args);
2917
2926
  });
2918
- def("toBeCloseTo", function(number, numDigits = 2) {
2919
- utils.expectTypes(this, ["number"]);
2920
- return this.closeTo(number, numDigits);
2927
+ def("toBeCloseTo", function(received, precision = 2) {
2928
+ const expected = this._obj;
2929
+ let pass = false;
2930
+ let expectedDiff = 0;
2931
+ let receivedDiff = 0;
2932
+ if (received === Infinity && expected === Infinity) {
2933
+ pass = true;
2934
+ } else if (received === -Infinity && expected === -Infinity) {
2935
+ pass = true;
2936
+ } else {
2937
+ expectedDiff = Math.pow(10, -precision) / 2;
2938
+ receivedDiff = Math.abs(expected - received);
2939
+ pass = receivedDiff < expectedDiff;
2940
+ }
2941
+ return this.assert(pass, `expected #{this} to be close to #{exp}, recieved difference is ${receivedDiff}, but expected ${expectedDiff}`, `expected #{this} to not be close to #{exp}, recieved difference is ${receivedDiff}, but expected ${expectedDiff}`, received, expected);
2921
2942
  });
2922
- function isSpy(putativeSpy) {
2923
- return typeof putativeSpy === "function" && "__isSpy" in putativeSpy && putativeSpy.__isSpy;
2924
- }
2925
2943
  const assertIsMock = (assertion) => {
2926
- if (!isSpy(assertion._obj))
2944
+ if (!isMockFunction(assertion._obj))
2927
2945
  throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`);
2928
2946
  };
2929
2947
  const getSpy = (assertion) => {
@@ -2933,23 +2951,26 @@ const JestChaiExpect = (chai, utils) => {
2933
2951
  def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) {
2934
2952
  const spy = getSpy(this);
2935
2953
  const spyName = spy.getMockName();
2936
- return this.assert(spy.callCount === number, `expected "${spyName}" to be called #{exp} times`, `expected "${spyName}" to not be called #{exp} times`, number, spy.callCount);
2954
+ const callCount = spy.mock.calls.length;
2955
+ return this.assert(callCount === number, `expected "${spyName}" to be called #{exp} times`, `expected "${spyName}" to not be called #{exp} times`, number, callCount);
2937
2956
  });
2938
2957
  def("toHaveBeenCalledOnce", function() {
2939
2958
  const spy = getSpy(this);
2940
2959
  const spyName = spy.getMockName();
2941
- return this.assert(spy.callCount === 1, `expected "${spyName}" to be called once`, `expected "${spyName}" to not be called once`, 1, spy.callCount);
2960
+ const callCount = spy.mock.calls.length;
2961
+ return this.assert(callCount === 1, `expected "${spyName}" to be called once`, `expected "${spyName}" to not be called once`, 1, callCount);
2942
2962
  });
2943
2963
  def(["toHaveBeenCalled", "toBeCalled"], function() {
2944
2964
  const spy = getSpy(this);
2945
2965
  const spyName = spy.getMockName();
2946
- return this.assert(spy.called, `expected "${spyName}" to be called at least once`, `expected "${spyName}" to not be called at all`, true, spy.called);
2966
+ const called = spy.mock.calls.length > 0;
2967
+ return this.assert(called, `expected "${spyName}" to be called at least once`, `expected "${spyName}" to not be called at all`, true, called);
2947
2968
  });
2948
2969
  def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) {
2949
2970
  const spy = getSpy(this);
2950
2971
  const spyName = spy.getMockName();
2951
- const pass = spy.calls.some((callArg) => equals(callArg, args, [iterableEquality]));
2952
- return this.assert(pass, `expected "${spyName}" to be called with arguments: #{exp}`, `expected "${spyName}" to not be called with arguments: #{exp}`, args, spy.calls);
2972
+ const pass = spy.mock.calls.some((callArg) => equals(callArg, args, [iterableEquality]));
2973
+ return this.assert(pass, `expected "${spyName}" to be called with arguments: #{exp}`, `expected "${spyName}" to not be called with arguments: #{exp}`, args, spy.mock.calls);
2953
2974
  });
2954
2975
  const ordinalOf = (i) => {
2955
2976
  const j = i % 10;
@@ -2965,44 +2986,40 @@ const JestChaiExpect = (chai, utils) => {
2965
2986
  def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) {
2966
2987
  const spy = getSpy(this);
2967
2988
  const spyName = spy.getMockName();
2968
- const nthCall = spy.calls[times - 1];
2989
+ const nthCall = spy.mock.calls[times - 1];
2969
2990
  this.assert(equals(nthCall, args, [iterableEquality]), `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}`, `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall);
2970
2991
  });
2971
2992
  def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) {
2972
2993
  const spy = getSpy(this);
2973
2994
  const spyName = spy.getMockName();
2974
- const lastCall = spy.calls[spy.calls.length - 1];
2995
+ const lastCall = spy.mock.calls[spy.calls.length - 1];
2975
2996
  this.assert(equals(lastCall, args, [iterableEquality]), `expected last "${spyName}" call to have been called with #{exp}`, `expected last "${spyName}" call to not have been called with #{exp}`, args, lastCall);
2976
2997
  });
2977
2998
  def(["toThrow", "toThrowError"], function(expected) {
2978
- const negate = utils.flag(this, "negate");
2979
- if (negate)
2980
- this.not.to.throw(expected);
2981
- else
2982
- this.to.throw(expected);
2999
+ return this.to.throw(expected);
2983
3000
  });
2984
3001
  def(["toHaveReturned", "toReturn"], function() {
2985
3002
  const spy = getSpy(this);
2986
3003
  const spyName = spy.getMockName();
2987
- const calledAndNotThrew = spy.called && !spy.results.some(([type]) => type === "error");
3004
+ const calledAndNotThrew = spy.mock.calls.length > 0 && !spy.mock.results.some(({ type }) => type === "throw");
2988
3005
  this.assert(calledAndNotThrew, `expected "${spyName}" to be successfully called at least once`, `expected "${spyName}" to not be successfully called`, calledAndNotThrew, !calledAndNotThrew);
2989
3006
  });
2990
3007
  def(["toHaveReturnedTimes", "toReturnTimes"], function(times) {
2991
3008
  const spy = getSpy(this);
2992
3009
  const spyName = spy.getMockName();
2993
- const successfullReturns = spy.results.reduce((success, [type]) => type === "error" ? success : ++success, 0);
3010
+ const successfullReturns = spy.mock.results.reduce((success, { type }) => type === "throw" ? success : ++success, 0);
2994
3011
  this.assert(successfullReturns === times, `expected "${spyName}" to be successfully called ${times} times`, `expected "${spyName}" to not be successfully called ${times} times`, `expected number of returns: ${times}`, `received number of returns: ${successfullReturns}`);
2995
3012
  });
2996
3013
  def(["toHaveReturnedWith", "toReturnWith"], function(value) {
2997
3014
  const spy = getSpy(this);
2998
3015
  const spyName = spy.getMockName();
2999
- const pass = spy.results.some(([type, result]) => type === "ok" && equals(value, result));
3016
+ const pass = spy.mock.results.some(({ type, value: result }) => type === "return" && equals(value, result));
3000
3017
  this.assert(pass, `expected "${spyName}" to be successfully called with #{exp}`, `expected "${spyName}" to not be successfully called with #{exp}`, value);
3001
3018
  });
3002
3019
  def(["toHaveLastReturnedWith", "lastReturnedWith"], function(value) {
3003
3020
  const spy = getSpy(this);
3004
3021
  const spyName = spy.getMockName();
3005
- const lastResult = spy.returns[spy.returns.length - 1];
3022
+ const { value: lastResult } = spy.mock.results[spy.returns.length - 1];
3006
3023
  const pass = equals(lastResult, value);
3007
3024
  this.assert(pass, `expected last "${spyName}" call to return #{exp}`, `expected last "${spyName}" call to not return #{exp}`, value, lastResult);
3008
3025
  });
@@ -3010,9 +3027,9 @@ const JestChaiExpect = (chai, utils) => {
3010
3027
  const spy = getSpy(this);
3011
3028
  const spyName = spy.getMockName();
3012
3029
  const isNot = utils.flag(this, "negate");
3013
- const [callType, callResult] = spy.results[nthCall - 1];
3030
+ const { type: callType, value: callResult } = spy.mock.results[nthCall - 1];
3014
3031
  const ordinalCall = `${ordinalOf(nthCall)} call`;
3015
- if (!isNot && callType === "error")
3032
+ if (!isNot && callType === "throw")
3016
3033
  chai.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`);
3017
3034
  const nthCallReturn = equals(callResult, value);
3018
3035
  this.assert(nthCallReturn, `expected ${ordinalCall} "${spyName}" call to return #{exp}`, `expected ${ordinalCall} "${spyName}" call to not return #{exp}`, value, callResult);
@@ -3030,7 +3047,7 @@ const JestChaiExpect = (chai, utils) => {
3030
3047
  utils.flag(this, "object", value);
3031
3048
  return result.call(this, ...args);
3032
3049
  }, (err) => {
3033
- throw new Error(`promise rejected ${err} instead of resolving`);
3050
+ throw new Error(`promise rejected "${err}" instead of resolving`);
3034
3051
  });
3035
3052
  };
3036
3053
  }
@@ -3048,7 +3065,7 @@ const JestChaiExpect = (chai, utils) => {
3048
3065
  return result instanceof chai.Assertion ? proxy : result;
3049
3066
  return async (...args) => {
3050
3067
  return wrapper.then((value) => {
3051
- throw new Error(`promise resolved ${value} instead of rejecting`);
3068
+ throw new Error(`promise resolved "${value}" instead of rejecting`);
3052
3069
  }, (err) => {
3053
3070
  utils.flag(this, "object", err);
3054
3071
  return result.call(this, ...args);
@@ -3362,7 +3379,7 @@ class FakeTimers {
3362
3379
  this._setInterval,
3363
3380
  this._clearTimeout,
3364
3381
  this._clearInterval
3365
- ], 'timers are not mocked. try calling "vitest.useFakeTimers()" first');
3382
+ ], 'timers are not mocked. try calling "vi.useFakeTimers()" first');
3366
3383
  }
3367
3384
  }
3368
3385
 
@@ -3419,7 +3436,7 @@ class VitestUtils {
3419
3436
  return item;
3420
3437
  }
3421
3438
  isMockFunction(fn2) {
3422
- return typeof fn2 === "function" && "__isSpy" in fn2 && fn2.__isSpy;
3439
+ return isMockFunction(fn2);
3423
3440
  }
3424
3441
  clearAllMocks() {
3425
3442
  __vitest__clearMocks__({ clearMocks: true });
package/dist/worker.js CHANGED
@@ -1,12 +1,12 @@
1
- import { d as dirname, b as basename, k as resolve, p as mergeSlashes, q as join, s as slash, m as toFilePath } from './index-250bdca0.js';
1
+ import { d as dirname, b as basename, k as resolve, p as mergeSlashes, q as join, s as slash, m as toFilePath } from './index-f0488a5d.js';
2
2
  import { c as createBirpc } from './index-e909c175.js';
3
- import { c as distDir } from './constants-744cb76d.js';
3
+ import { c as distDir } from './constants-2cd49e0a.js';
4
4
  import { builtinModules, createRequire } from 'module';
5
5
  import { pathToFileURL, fileURLToPath } from 'url';
6
6
  import vm from 'vm';
7
7
  import { s as shouldExternalize } from './externalize-2f63779d.js';
8
8
  import { existsSync, readdirSync } from 'fs';
9
- import { a as spyOn, s as spies } from './jest-mock-038a01b3.js';
9
+ import { a as spyOn, s as spies } from './jest-mock-30625866.js';
10
10
  import { r as rpc } from './rpc-8c7cc374.js';
11
11
  import 'tty';
12
12
  import 'local-pkg';
@@ -383,7 +383,7 @@ async function startViteNode(ctx) {
383
383
  return _viteNode;
384
384
  }
385
385
  function init(ctx) {
386
- if (process.__vitest_worker__ && ctx.config.threads)
386
+ if (process.__vitest_worker__ && ctx.config.threads && ctx.config.isolate)
387
387
  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.`);
388
388
  process.stdout.write("\0");
389
389
  const { config, port } = ctx;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitest",
3
- "version": "0.0.123",
3
+ "version": "0.0.127",
4
4
  "description": "A blazing fast unit test framework powered by Vite",
5
5
  "keywords": [
6
6
  "vite",
@@ -8,13 +8,13 @@
8
8
  "test",
9
9
  "jest"
10
10
  ],
11
- "homepage": "https://github.com/antfu/vitest#readme",
11
+ "homepage": "https://github.com/vitest-dev/vitest#readme",
12
12
  "bugs": {
13
- "url": "https://github.com/antfu/vitest/issues"
13
+ "url": "https://github.com/vitest-dev/vitest/issues"
14
14
  },
15
15
  "repository": {
16
16
  "type": "git",
17
- "url": "git+https://github.com/antfu/vitest.git"
17
+ "url": "git+https://github.com/vitest-dev/vitest.git"
18
18
  },
19
19
  "funding": "https://github.com/sponsors/antfu",
20
20
  "license": "MIT",
@@ -91,7 +91,7 @@
91
91
  "strip-ansi": "^7.0.1",
92
92
  "typescript": "^4.5.4",
93
93
  "ws": "^8.4.0",
94
- "@vitest/ui": "0.0.123"
94
+ "@vitest/ui": "0.0.127"
95
95
  },
96
96
  "peerDependencies": {
97
97
  "c8": "*",
@@ -120,5 +120,5 @@
120
120
  "build": "rimraf dist && rollup -c",
121
121
  "dev": "rollup -c --watch src"
122
122
  },
123
- "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"
123
+ "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[GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/)\n"
124
124
  }