vitest 3.2.0-beta.2 → 3.2.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 (72) hide show
  1. package/LICENSE.md +29 -0
  2. package/dist/browser.d.ts +3 -3
  3. package/dist/browser.js +2 -2
  4. package/dist/chunks/{base.DwtwORaC.js → base.Cg0miDlQ.js} +11 -14
  5. package/dist/chunks/{benchmark.BoF7jW0Q.js → benchmark.CYdenmiT.js} +4 -6
  6. package/dist/chunks/{cac.I9MLYfT-.js → cac.6rXCxFY1.js} +76 -143
  7. package/dist/chunks/{cli-api.d6IK1pnk.js → cli-api.Cej3MBjA.js} +1460 -1344
  8. package/dist/chunks/{config.d.UqE-KR0o.d.ts → config.d.D2ROskhv.d.ts} +2 -0
  9. package/dist/chunks/{console.K1NMVOSc.js → console.CtFJOzRO.js} +25 -45
  10. package/dist/chunks/{constants.BZZyIeIE.js → constants.DnKduX2e.js} +1 -0
  11. package/dist/chunks/{coverage.0iPg4Wrz.js → coverage.DVF1vEu8.js} +4 -12
  12. package/dist/chunks/{coverage.OGU09Jbh.js → coverage.EIiagJJP.js} +578 -993
  13. package/dist/chunks/{creator.DGAdZ4Hj.js → creator.GK6I-cL4.js} +39 -83
  14. package/dist/chunks/date.Bq6ZW5rf.js +73 -0
  15. package/dist/chunks/{defaults.DSxsTG0h.js → defaults.B7q_naMc.js} +2 -1
  16. package/dist/chunks/{env.Dq0hM4Xv.js → env.D4Lgay0q.js} +1 -1
  17. package/dist/chunks/{environment.d.D8YDy2v5.d.ts → environment.d.cL3nLXbE.d.ts} +1 -0
  18. package/dist/chunks/{execute.JlGHLJZT.js → execute.B7h3T_Hc.js} +126 -217
  19. package/dist/chunks/{git.DXfdBEfR.js → git.BVQ8w_Sw.js} +1 -3
  20. package/dist/chunks/{global.d.BPa1eL3O.d.ts → global.d.MAmajcmJ.d.ts} +5 -1
  21. package/dist/chunks/{globals.CpxW8ccg.js → globals.DEHgCU4V.js} +7 -6
  22. package/dist/chunks/{index.CV36oG_L.js → index.BZ0g1JD2.js} +430 -625
  23. package/dist/chunks/{index.DswW_LEs.js → index.BbB8_kAK.js} +25 -24
  24. package/dist/chunks/{index.CmC5OK9L.js → index.CIyJn3t1.js} +38 -82
  25. package/dist/chunks/{index.CfXMNXHg.js → index.CdQS2e2Q.js} +4 -2
  26. package/dist/chunks/{index.DFXFpH3w.js → index.CmSc2RE5.js} +85 -105
  27. package/dist/chunks/index.D3XRDfWc.js +213 -0
  28. package/dist/chunks/{inspector.DbDkSkFn.js → inspector.C914Efll.js} +4 -1
  29. package/dist/chunks/{node.3xsWotC9.js → node.fjCdwEIl.js} +1 -1
  30. package/dist/chunks/{reporters.d.CLC9rhKy.d.ts → reporters.d.C1ogPriE.d.ts} +47 -9
  31. package/dist/chunks/{rpc.D9_013TY.js → rpc.Iovn4oWe.js} +10 -19
  32. package/dist/chunks/{runBaseTests.Dn2vyej_.js → runBaseTests.Dd85QTll.js} +27 -31
  33. package/dist/chunks/{setup-common.CYo3Y0dD.js → setup-common.Dd054P77.js} +16 -42
  34. package/dist/chunks/{typechecker.DnTrplSJ.js → typechecker.DRKU1-1g.js} +163 -186
  35. package/dist/chunks/{utils.BfxieIyZ.js → utils.CAioKnHs.js} +9 -14
  36. package/dist/chunks/{utils.CgTj3MsC.js → utils.XdZDrNZV.js} +6 -13
  37. package/dist/chunks/{vi.BFR5YIgu.js → vi.bdSIJ99Y.js} +137 -263
  38. package/dist/chunks/{vite.d.CBZ3M_ru.d.ts → vite.d.DqE4-hhK.d.ts} +3 -1
  39. package/dist/chunks/{vm.C1HHjtNS.js → vm.BThCzidc.js} +164 -212
  40. package/dist/chunks/{worker.d.D5Xdi-Zr.d.ts → worker.d.DvqK5Vmu.d.ts} +1 -1
  41. package/dist/chunks/{worker.d.CoCI7hzP.d.ts → worker.d.tQu2eJQy.d.ts} +5 -3
  42. package/dist/cli.js +5 -5
  43. package/dist/config.cjs +3 -1
  44. package/dist/config.d.ts +7 -6
  45. package/dist/config.js +3 -3
  46. package/dist/coverage.d.ts +4 -4
  47. package/dist/coverage.js +7 -7
  48. package/dist/environments.d.ts +6 -2
  49. package/dist/environments.js +1 -1
  50. package/dist/execute.d.ts +9 -3
  51. package/dist/execute.js +1 -1
  52. package/dist/index.d.ts +28 -15
  53. package/dist/index.js +5 -5
  54. package/dist/node.d.ts +18 -10
  55. package/dist/node.js +17 -17
  56. package/dist/reporters.d.ts +4 -4
  57. package/dist/reporters.js +4 -4
  58. package/dist/runners.d.ts +6 -3
  59. package/dist/runners.js +59 -80
  60. package/dist/snapshot.js +2 -2
  61. package/dist/suite.js +2 -2
  62. package/dist/worker.js +39 -41
  63. package/dist/workers/forks.js +6 -4
  64. package/dist/workers/runVmTests.js +20 -21
  65. package/dist/workers/threads.js +4 -4
  66. package/dist/workers/vmForks.js +6 -6
  67. package/dist/workers/vmThreads.js +6 -6
  68. package/dist/workers.d.ts +4 -4
  69. package/dist/workers.js +10 -10
  70. package/package.json +21 -19
  71. package/dist/chunks/date.CDOsz-HY.js +0 -53
  72. package/dist/chunks/index.CK1YOQaa.js +0 -143
@@ -1,13 +1,13 @@
1
- import { Task, TaskMeta, Suite, File, TaskResultPack, SequenceSetupFiles, SequenceHooks, CancelReason } from '@vitest/runner';
2
- import { b as Awaitable, U as UserConsoleLog, c as Arrayable$1, A as AfterSuiteRunMeta, L as LabelColor, f as EnvironmentOptions, P as ProvidedContext } from './environment.d.D8YDy2v5.js';
1
+ import { Task, TaskMeta, Suite, File, TestAnnotation, ImportDuration, TaskResultPack, TaskEventPack, SequenceSetupFiles, SequenceHooks, CancelReason } from '@vitest/runner';
2
+ import { b as Awaitable, U as UserConsoleLog, c as Arrayable$1, A as AfterSuiteRunMeta, L as LabelColor, f as EnvironmentOptions, P as ProvidedContext } from './environment.d.cL3nLXbE.js';
3
3
  import { ParsedStack, TestError, SerializedError, ErrorWithDiff, Arrayable, Awaitable as Awaitable$1 } from '@vitest/utils';
4
4
  import { Writable } from 'node:stream';
5
5
  import { TransformResult as TransformResult$1, UserConfig as UserConfig$1, DepOptimizationConfig, ServerOptions, ConfigEnv, AliasOptions, ViteDevServer, ModuleNode } from 'vite';
6
6
  import { Console } from 'node:console';
7
7
  import { MockedModule } from '@vitest/mocker';
8
8
  import { StackTraceParserOptions } from '@vitest/utils/source-map';
9
- import { T as TestExecutionMethod } from './worker.d.CoCI7hzP.js';
10
- import { a as SerializedConfig, F as FakeTimerInstallOpts } from './config.d.UqE-KR0o.js';
9
+ import { T as TestExecutionMethod } from './worker.d.tQu2eJQy.js';
10
+ import { a as SerializedConfig, F as FakeTimerInstallOpts } from './config.d.D2ROskhv.js';
11
11
  import { PrettyFormatOptions } from '@vitest/pretty-format';
12
12
  import { SnapshotSummary, SnapshotStateOptions } from '@vitest/snapshot';
13
13
  import { SerializedDiffOptions } from '@vitest/utils/diff';
@@ -133,6 +133,10 @@ declare class TestCase extends ReportedTaskImplementation {
133
133
  */
134
134
  result(): TestResult;
135
135
  /**
136
+ * Test annotations added via the `task.annotate` API during the test execution.
137
+ */
138
+ annotations(): ReadonlyArray<TestAnnotation>;
139
+ /**
136
140
  * Useful information about the test like duration, memory usage, etc.
137
141
  * Diagnostic is only available after the test has finished.
138
142
  */
@@ -373,6 +377,10 @@ interface ModuleDiagnostic {
373
377
  * This value is only available if the test was executed with `logHeapUsage` flag.
374
378
  */
375
379
  readonly heap: number | undefined;
380
+ /**
381
+ * The time spent importing every non-externalized dependency that Vitest has processed.
382
+ */
383
+ readonly importDurations: Record<string, ImportDuration>;
376
384
  }
377
385
 
378
386
  type BuiltinPool = "browser" | "threads" | "forks" | "vmThreads" | "vmForks" | "typescript";
@@ -573,7 +581,7 @@ interface Reporter {
573
581
  /**
574
582
  * @deprecated use `onTestModuleQueued`, `onTestModuleStart`, `onTestModuleEnd`, `onTestCaseReady`, `onTestCaseResult` instead
575
583
  */
576
- onTaskUpdate?: (packs: TaskResultPack[]) => Awaitable<void>;
584
+ onTaskUpdate?: (packs: TaskResultPack[], events: TaskEventPack[]) => Awaitable<void>;
577
585
  onTestRemoved?: (trigger?: string) => Awaitable<void>;
578
586
  onWatcherStart?: (files?: File[], errors?: unknown[]) => Awaitable<void>;
579
587
  onWatcherRerun?: (files: string[], trigger?: string) => Awaitable<void>;
@@ -615,6 +623,10 @@ interface Reporter {
615
623
  */
616
624
  onTestCaseResult?: (testCase: TestCase) => Awaitable<void>;
617
625
  /**
626
+ * Called when annotation is added via the `task.annotate` API.
627
+ */
628
+ onTestCaseAnnotate?: (testCase: TestCase, annotation: TestAnnotation) => Awaitable<void>;
629
+ /**
618
630
  * Called when test suite is ready to run.
619
631
  * Called before the `beforeAll` hooks for the test are run.
620
632
  */
@@ -666,6 +678,7 @@ declare abstract class BaseReporter implements Reporter {
666
678
  protected getTestName(test: Task, separator?: string): string;
667
679
  protected formatShortError(error: ErrorWithDiff): string;
668
680
  protected getTestIndentation(_test: Task): string;
681
+ protected printAnnotations(test: TestCase, console: "log" | "error", padding?: number): void;
669
682
  protected getDurationPrefix(task: Task): string;
670
683
  onWatcherStart(files?: File[], errors?: unknown[]): void;
671
684
  onWatcherRerun(files: string[], trigger?: string): void;
@@ -714,7 +727,6 @@ declare class DefaultReporter extends BaseReporter {
714
727
  onHookStart(hook: ReportedHookContext): void;
715
728
  onHookEnd(hook: ReportedHookContext): void;
716
729
  onInit(ctx: Vitest): void;
717
- onPathsCollected(paths?: string[]): void;
718
730
  onTestRunEnd(): void;
719
731
  }
720
732
 
@@ -826,6 +838,9 @@ declare class FileCoverage implements FileCoverageData {
826
838
  b: { [key: string]: number[] };
827
839
  }
828
840
 
841
+ // for compatibility reasons, the reporter produces a JSON similar to the one produced by the Jest JSON reporter
842
+ // the following types are extracted from the Jest repository (and simplified)
843
+ // the commented-out fields are the missing ones
829
844
  type Status = "passed" | "failed" | "skipped" | "pending" | "todo" | "disabled";
830
845
  type Milliseconds = number;
831
846
  interface Callsite {
@@ -946,9 +961,15 @@ declare class DotReporter extends BaseReporter {
946
961
  private createSummary;
947
962
  }
948
963
 
964
+ interface GithubActionsReporterOptions {
965
+ onWritePath?: (path: string) => string;
966
+ }
949
967
  declare class GithubActionsReporter implements Reporter {
950
968
  ctx: Vitest;
969
+ options: GithubActionsReporterOptions;
970
+ constructor(options?: GithubActionsReporterOptions);
951
971
  onInit(ctx: Vitest): void;
972
+ onTestCaseAnnotate(testCase: TestCase, annotation: TestAnnotation): void;
952
973
  onFinished(files?: File[], errors?: unknown[]): void;
953
974
  }
954
975
 
@@ -1425,6 +1446,7 @@ interface Thresholds {
1425
1446
  }
1426
1447
 
1427
1448
  type BuiltinEnvironment = "node" | "jsdom" | "happy-dom" | "edge-runtime";
1449
+ // Record is used, so user can get intellisense for builtin environments, but still allow custom environments
1428
1450
  type VitestEnvironment = BuiltinEnvironment | (string & Record<never, never>);
1429
1451
 
1430
1452
  type CSSModuleScopeStrategy = "stable" | "scoped" | "non-scoped";
@@ -1974,7 +1996,7 @@ interface InlineConfig {
1974
1996
  maxConcurrency?: number;
1975
1997
  /**
1976
1998
  * Options for configuring cache policy.
1977
- * @default { dir: 'node_modules/.vite/vitest' }
1999
+ * @default { dir: 'node_modules/.vite/vitest/{project-hash}' }
1978
2000
  */
1979
2001
  cache?: false | {
1980
2002
  /**
@@ -2132,6 +2154,12 @@ interface InlineConfig {
2132
2154
  * @default false
2133
2155
  */
2134
2156
  includeTaskLocation?: boolean;
2157
+ /**
2158
+ * Directory path for storing attachments created by `context.annotate`
2159
+ *
2160
+ * @default '.vitest-attachments'
2161
+ */
2162
+ attachmentsDir?: string;
2135
2163
  }
2136
2164
  interface TypecheckConfig {
2137
2165
  /**
@@ -2173,6 +2201,11 @@ interface TypecheckConfig {
2173
2201
  * Path to tsconfig, relative to the project root.
2174
2202
  */
2175
2203
  tsconfig?: string;
2204
+ /**
2205
+ * Minimum time in milliseconds it takes to spawn the typechecker.
2206
+ * @default 10_000
2207
+ */
2208
+ spawnTimeout?: number;
2176
2209
  }
2177
2210
  interface UserConfig extends InlineConfig {
2178
2211
  /**
@@ -2351,6 +2384,7 @@ interface BrowserProvider {
2351
2384
  openPage: (sessionId: string, url: string, beforeNavigate?: () => Promise<void>) => Promise<void>;
2352
2385
  getCDPSession?: (sessionId: string) => Promise<CDPSession>;
2353
2386
  close: () => Awaitable$1<void>;
2387
+ // eslint-disable-next-line ts/method-signature-style -- we want to allow extended options
2354
2388
  initialize(ctx: TestProject, options: BrowserProviderInitializationOptions): Awaitable$1<void>;
2355
2389
  }
2356
2390
  interface BrowserProviderModule {
@@ -2613,6 +2647,8 @@ declare class TestProject {
2613
2647
  * It is based on the root of the project (not consistent between OS) and its name.
2614
2648
  */
2615
2649
  get hash(): string;
2650
+ // "provide" is a property, not a method to keep the context when destructed in the global setup,
2651
+ // making it a method would be a breaking change, and can be done in Vitest 3 at minimum
2616
2652
  /**
2617
2653
  * Provide a value to the test context. This value will be available to all tests with `inject`.
2618
2654
  */
@@ -2664,6 +2700,7 @@ declare class TestProject {
2664
2700
  teardownGlobalSetup(): Promise<void>;
2665
2701
  /** @deprecated use `vitest.logger` instead */
2666
2702
  get logger(): Logger;
2703
+ // it's possible that file path was imported with different queries (?raw, ?url, etc)
2667
2704
  /** @deprecated use `.vite` or `.browser.vite` directly */
2668
2705
  getModulesByFilepath(file: string): Set<ModuleNode>;
2669
2706
  /** @deprecated use `.vite` or `.browser.vite` directly */
@@ -2879,7 +2916,7 @@ declare class Vitest {
2879
2916
  private _cache?;
2880
2917
  private _snapshot?;
2881
2918
  private _workspaceConfigPath?;
2882
- constructor(mode: VitestRunMode, options?: VitestOptions);
2919
+ constructor(mode: VitestRunMode, cliOptions: UserConfig, options?: VitestOptions);
2883
2920
  private _onRestartListeners;
2884
2921
  private _onClose;
2885
2922
  private _onSetServer;
@@ -2914,7 +2951,7 @@ declare class Vitest {
2914
2951
  */
2915
2952
  get cache(): VitestCache;
2916
2953
  /** @deprecated internal */
2917
- setServer(options: UserConfig, server: ViteDevServer, cliOptions: UserConfig): Promise<void>;
2954
+ setServer(options: UserConfig, server: ViteDevServer): Promise<void>;
2918
2955
  /**
2919
2956
  * Inject new test projects into the workspace.
2920
2957
  * @param config Glob, config path or a custom config options.
@@ -3046,6 +3083,7 @@ declare class Vitest {
3046
3083
  */
3047
3084
  resetGlobalTestNamePattern(): void;
3048
3085
  private _rerunTimer;
3086
+ // we can't use a single `triggerId` yet because vscode extension relies on this
3049
3087
  private scheduleRerun;
3050
3088
  /**
3051
3089
  * Invalidate a file in all projects.
@@ -1,6 +1,6 @@
1
1
  import { getSafeTimers } from '@vitest/utils';
2
2
  import { c as createBirpc } from './index.CJ0plNrh.js';
3
- import { g as getWorkerState } from './utils.CgTj3MsC.js';
3
+ import { g as getWorkerState } from './utils.XdZDrNZV.js';
4
4
 
5
5
  const { get } = Reflect;
6
6
  function withSafeTimers(fn) {
@@ -15,9 +15,7 @@ function withSafeTimers(fn) {
15
15
  globalThis.clearTimeout = clearTimeout;
16
16
  globalThis.setImmediate = setImmediate;
17
17
  globalThis.clearImmediate = clearImmediate;
18
- if (globalThis.process) {
19
- globalThis.process.nextTick = nextTick;
20
- }
18
+ if (globalThis.process) globalThis.process.nextTick = nextTick;
21
19
  const result = fn();
22
20
  return result;
23
21
  } finally {
@@ -25,18 +23,14 @@ function withSafeTimers(fn) {
25
23
  globalThis.clearTimeout = currentClearTimeout;
26
24
  globalThis.setImmediate = currentSetImmediate;
27
25
  globalThis.clearImmediate = currentClearImmediate;
28
- if (globalThis.process) {
29
- nextTick(() => {
30
- globalThis.process.nextTick = currentNextTick;
31
- });
32
- }
26
+ if (globalThis.process) nextTick(() => {
27
+ globalThis.process.nextTick = currentNextTick;
28
+ });
33
29
  }
34
30
  }
35
- const promises = new Set();
31
+ const promises = /* @__PURE__ */ new Set();
36
32
  async function rpcDone() {
37
- if (!promises.size) {
38
- return;
39
- }
33
+ if (!promises.size) return;
40
34
  const awaitable = Array.from(promises);
41
35
  return Promise.all(awaitable);
42
36
  }
@@ -53,12 +47,9 @@ function createRuntimeRpc(options) {
53
47
  ],
54
48
  onTimeoutError(functionName, args) {
55
49
  let message = `[vitest-worker]: Timeout calling "${functionName}"`;
56
- if (functionName === "fetch" || functionName === "transform" || functionName === "resolveId") {
57
- message += ` with "${JSON.stringify(args)}"`;
58
- }
59
- if (functionName === "onUnhandledError") {
60
- message += ` with "${args[0]?.message || args[0]}"`;
61
- }
50
+ if (functionName === "fetch" || functionName === "transform" || functionName === "resolveId") message += ` with "${JSON.stringify(args)}"`;
51
+ // JSON.stringify cannot serialize Error instances
52
+ if (functionName === "onUnhandledError") message += ` with "${args[0]?.message || args[0]}"`;
62
53
  throw new Error(message);
63
54
  },
64
55
  ...options
@@ -1,9 +1,9 @@
1
1
  import { performance } from 'node:perf_hooks';
2
2
  import { startTests, collectTests } from '@vitest/runner';
3
- import { a as resolveSnapshotEnvironment, s as setupChaiConfig, r as resolveTestRunner } from './index.DswW_LEs.js';
4
- import { c as setupCommonEnv, s as startCoverageInsideWorker, a as stopCoverageInsideWorker } from './setup-common.CYo3Y0dD.js';
5
- import { a as globalExpect, v as vi } from './vi.BFR5YIgu.js';
6
- import { c as closeInspector } from './inspector.DbDkSkFn.js';
3
+ import { a as resolveSnapshotEnvironment, s as setupChaiConfig, r as resolveTestRunner } from './index.BbB8_kAK.js';
4
+ import { c as setupCommonEnv, s as startCoverageInsideWorker, a as stopCoverageInsideWorker } from './setup-common.Dd054P77.js';
5
+ import { a as globalExpect, v as vi } from './vi.bdSIJ99Y.js';
6
+ import { c as closeInspector } from './inspector.C914Efll.js';
7
7
  import { createRequire } from 'node:module';
8
8
  import timers from 'node:timers';
9
9
  import timersPromises from 'node:timers/promises';
@@ -11,15 +11,15 @@ import util from 'node:util';
11
11
  import { getSafeTimers } from '@vitest/utils';
12
12
  import { KNOWN_ASSET_TYPES } from 'vite-node/constants';
13
13
  import { installSourcemapsSupport } from 'vite-node/source-map';
14
- import { V as VitestIndex } from './index.CfXMNXHg.js';
15
- import { g as getWorkerState, r as resetModules } from './utils.CgTj3MsC.js';
14
+ import { V as VitestIndex } from './index.CdQS2e2Q.js';
15
+ import { g as getWorkerState, r as resetModules } from './utils.XdZDrNZV.js';
16
16
  import 'chai';
17
17
  import 'node:path';
18
18
  import '../path.js';
19
19
  import 'node:url';
20
- import './rpc.D9_013TY.js';
20
+ import './rpc.Iovn4oWe.js';
21
21
  import './index.CJ0plNrh.js';
22
- import './coverage.0iPg4Wrz.js';
22
+ import './coverage.DVF1vEu8.js';
23
23
  import '@vitest/snapshot';
24
24
  import '@vitest/expect';
25
25
  import '@vitest/runner/utils';
@@ -27,10 +27,11 @@ import './_commonjsHelpers.BFTU3MAI.js';
27
27
  import '@vitest/utils/error';
28
28
  import '@vitest/spy';
29
29
  import '@vitest/utils/source-map';
30
- import './date.CDOsz-HY.js';
31
- import './benchmark.BoF7jW0Q.js';
30
+ import './date.Bq6ZW5rf.js';
31
+ import './benchmark.CYdenmiT.js';
32
32
  import 'expect-type';
33
33
 
34
+ // this should only be used in Node
34
35
  let globalSetup = false;
35
36
  async function setupGlobalEnv(config, { environment }, executor) {
36
37
  await setupCommonEnv(config);
@@ -39,35 +40,30 @@ async function setupGlobalEnv(config, { environment }, executor) {
39
40
  enumerable: false
40
41
  });
41
42
  const state = getWorkerState();
42
- if (!state.config.snapshotOptions.snapshotEnvironment) {
43
- state.config.snapshotOptions.snapshotEnvironment = await resolveSnapshotEnvironment(config, executor);
44
- }
45
- if (globalSetup) {
46
- return;
47
- }
43
+ if (!state.config.snapshotOptions.snapshotEnvironment) state.config.snapshotOptions.snapshotEnvironment = await resolveSnapshotEnvironment(config, executor);
44
+ if (globalSetup) return;
48
45
  globalSetup = true;
49
46
  if (environment.transformMode === "web") {
50
47
  const _require = createRequire(import.meta.url);
48
+ // always mock "required" `css` files, because we cannot process them
51
49
  _require.extensions[".css"] = resolveCss;
52
50
  _require.extensions[".scss"] = resolveCss;
53
51
  _require.extensions[".sass"] = resolveCss;
54
52
  _require.extensions[".less"] = resolveCss;
53
+ // since we are using Vite, we can assume how these will be resolved
55
54
  KNOWN_ASSET_TYPES.forEach((type) => {
56
55
  _require.extensions[`.${type}`] = resolveAsset;
57
56
  });
58
57
  process.env.SSR = "";
59
- } else {
60
- process.env.SSR = "1";
61
- }
58
+ } else process.env.SSR = "1";
59
+ // @ts-expect-error not typed global for patched timers
62
60
  globalThis.__vitest_required__ = {
63
61
  util,
64
62
  timers,
65
63
  timersPromises
66
64
  };
67
65
  installSourcemapsSupport({ getSourceMap: (source) => state.moduleCache.getSourceMap(source) });
68
- if (!config.disableConsoleIntercept) {
69
- await setupConsoleLogSpy();
70
- }
66
+ if (!config.disableConsoleIntercept) await setupConsoleLogSpy();
71
67
  }
72
68
  function resolveCss(mod) {
73
69
  mod.exports = "";
@@ -76,22 +72,25 @@ function resolveAsset(mod, url) {
76
72
  mod.exports = url;
77
73
  }
78
74
  async function setupConsoleLogSpy() {
79
- const { createCustomConsole } = await import('./console.K1NMVOSc.js');
75
+ const { createCustomConsole } = await import('./console.CtFJOzRO.js');
80
76
  globalThis.console = createCustomConsole();
81
77
  }
82
78
  async function withEnv({ environment }, options, fn) {
79
+ // @ts-expect-error untyped global
83
80
  globalThis.__vitest_environment__ = environment.name;
84
81
  globalExpect.setState({ environment: environment.name });
85
82
  const env = await environment.setup(globalThis, options);
86
83
  try {
87
84
  await fn();
88
85
  } finally {
86
+ // Run possible setTimeouts, e.g. the onces used by ConsoleLogSpy
89
87
  const { setTimeout } = getSafeTimers();
90
88
  await new Promise((resolve) => setTimeout(resolve));
91
89
  await env.teardown(globalThis);
92
90
  }
93
91
  }
94
92
 
93
+ // browser shouldn't call this!
95
94
  async function run(method, files, config, environment, executor) {
96
95
  const workerState = getWorkerState();
97
96
  const isIsolatedThreads = config.pool === "threads" && (config.poolOptions?.threads?.isolate ?? true);
@@ -99,9 +98,7 @@ async function run(method, files, config, environment, executor) {
99
98
  const isolate = isIsolatedThreads || isIsolatedForks;
100
99
  await setupGlobalEnv(config, environment, executor);
101
100
  await startCoverageInsideWorker(config.coverage, executor, { isolate });
102
- if (config.chaiConfig) {
103
- setupChaiConfig(config.chaiConfig);
104
- }
101
+ if (config.chaiConfig) setupChaiConfig(config.chaiConfig);
105
102
  const runner = await resolveTestRunner(config, executor);
106
103
  workerState.onCancel.then((reason) => {
107
104
  closeInspector(config);
@@ -117,12 +114,11 @@ async function run(method, files, config, environment, executor) {
117
114
  resetModules(workerState.moduleCache, true);
118
115
  }
119
116
  workerState.filepath = file.filepath;
120
- if (method === "run") {
121
- await startTests([file], runner);
122
- } else {
123
- await collectTests([file], runner);
124
- }
117
+ if (method === "run") await startTests([file], runner);
118
+ else await collectTests([file], runner);
119
+ // reset after tests, because user might call `vi.setConfig` in setupFile
125
120
  vi.resetConfig();
121
+ // mocks should not affect different files
126
122
  vi.restoreAllMocks();
127
123
  }
128
124
  await stopCoverageInsideWorker(config.coverage, executor, { isolate });
@@ -1,26 +1,20 @@
1
- import { r as resolveCoverageProviderModule } from './coverage.0iPg4Wrz.js';
1
+ import { r as resolveCoverageProviderModule } from './coverage.DVF1vEu8.js';
2
2
  import { addSerializer } from '@vitest/snapshot';
3
3
  import { setSafeTimers } from '@vitest/utils';
4
4
 
5
5
  async function startCoverageInsideWorker(options, loader, runtimeOptions) {
6
6
  const coverageModule = await resolveCoverageProviderModule(options, loader);
7
- if (coverageModule) {
8
- return coverageModule.startCoverage?.(runtimeOptions);
9
- }
7
+ if (coverageModule) return coverageModule.startCoverage?.(runtimeOptions);
10
8
  return null;
11
9
  }
12
10
  async function takeCoverageInsideWorker(options, loader) {
13
11
  const coverageModule = await resolveCoverageProviderModule(options, loader);
14
- if (coverageModule) {
15
- return coverageModule.takeCoverage?.({ moduleExecutionInfo: loader.moduleExecutionInfo });
16
- }
12
+ if (coverageModule) return coverageModule.takeCoverage?.({ moduleExecutionInfo: loader.moduleExecutionInfo });
17
13
  return null;
18
14
  }
19
15
  async function stopCoverageInsideWorker(options, loader, runtimeOptions) {
20
16
  const coverageModule = await resolveCoverageProviderModule(options, loader);
21
- if (coverageModule) {
22
- return coverageModule.stopCoverage?.(runtimeOptions);
23
- }
17
+ if (coverageModule) return coverageModule.stopCoverage?.(runtimeOptions);
24
18
  return null;
25
19
  }
26
20
 
@@ -28,56 +22,36 @@ let globalSetup = false;
28
22
  async function setupCommonEnv(config) {
29
23
  setupDefines(config.defines);
30
24
  setupEnv(config.env);
31
- if (globalSetup) {
32
- return;
33
- }
25
+ if (globalSetup) return;
34
26
  globalSetup = true;
35
27
  setSafeTimers();
36
- if (config.globals) {
37
- (await import('./globals.CpxW8ccg.js')).registerApiGlobally();
38
- }
28
+ if (config.globals) (await import('./globals.DEHgCU4V.js')).registerApiGlobally();
39
29
  }
40
30
  function setupDefines(defines) {
41
- for (const key in defines) {
42
- globalThis[key] = defines[key];
43
- }
31
+ for (const key in defines) globalThis[key] = defines[key];
44
32
  }
45
33
  function setupEnv(env) {
46
- if (typeof process === "undefined") {
47
- return;
48
- }
34
+ if (typeof process === "undefined") return;
35
+ // same boolean-to-string assignment as VitestPlugin.configResolved
49
36
  const { PROD, DEV,...restEnvs } = env;
50
37
  process.env.PROD = PROD ? "1" : "";
51
38
  process.env.DEV = DEV ? "1" : "";
52
- for (const key in restEnvs) {
53
- process.env[key] = env[key];
54
- }
39
+ for (const key in restEnvs) process.env[key] = env[key];
55
40
  }
56
41
  async function loadDiffConfig(config, executor) {
57
- if (typeof config.diff === "object") {
58
- return config.diff;
59
- }
60
- if (typeof config.diff !== "string") {
61
- return;
62
- }
42
+ if (typeof config.diff === "object") return config.diff;
43
+ if (typeof config.diff !== "string") return;
63
44
  const diffModule = await executor.executeId(config.diff);
64
- if (diffModule && typeof diffModule.default === "object" && diffModule.default != null) {
65
- return diffModule.default;
66
- } else {
67
- throw new Error(`invalid diff config file ${config.diff}. Must have a default export with config object`);
68
- }
45
+ if (diffModule && typeof diffModule.default === "object" && diffModule.default != null) return diffModule.default;
46
+ else throw new Error(`invalid diff config file ${config.diff}. Must have a default export with config object`);
69
47
  }
70
48
  async function loadSnapshotSerializers(config, executor) {
71
49
  const files = config.snapshotSerializers;
72
50
  const snapshotSerializers = await Promise.all(files.map(async (file) => {
73
51
  const mo = await executor.executeId(file);
74
- if (!mo || typeof mo.default !== "object" || mo.default === null) {
75
- throw new Error(`invalid snapshot serializer file ${file}. Must export a default object`);
76
- }
52
+ if (!mo || typeof mo.default !== "object" || mo.default === null) throw new Error(`invalid snapshot serializer file ${file}. Must export a default object`);
77
53
  const config = mo.default;
78
- if (typeof config.test !== "function" || typeof config.serialize !== "function" && typeof config.print !== "function") {
79
- throw new TypeError(`invalid snapshot serializer in ${file}. Must have a 'test' method along with either a 'serialize' or 'print' method.`);
80
- }
54
+ if (typeof config.test !== "function" || typeof config.serialize !== "function" && typeof config.print !== "function") throw new TypeError(`invalid snapshot serializer in ${file}. Must have a 'test' method along with either a 'serialize' or 'print' method.`);
81
55
  return config;
82
56
  }));
83
57
  snapshotSerializers.forEach((serializer) => addSerializer(serializer));