vitest 4.0.0-beta.7 → 4.0.0-beta.9

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 (56) hide show
  1. package/dist/browser.d.ts +5 -5
  2. package/dist/browser.js +4 -4
  3. package/dist/chunks/{runBaseTests.D6sfuWBM.js → base.CA5N8Af0.js} +55 -26
  4. package/dist/chunks/{benchmark.UW6Ezvxy.js → benchmark.CJUa-Hsa.js} +1 -1
  5. package/dist/chunks/{browser.d.DOMmqJQx.d.ts → browser.d.DtfyY9yS.d.ts} +1 -1
  6. package/dist/chunks/{cac.Dsn7ixFt.js → cac.Dt7e1TIu.js} +6 -25
  7. package/dist/chunks/{cli-api.DfGJyldU.js → cli-api.eAzsLIxz.js} +88 -209
  8. package/dist/chunks/{config.d._GBBbReY.d.ts → config.d.DacWrqWe.d.ts} +1 -0
  9. package/dist/chunks/{console.B0quX7yH.js → console.7h5kHUIf.js} +1 -1
  10. package/dist/chunks/{coverage.Dvxug1RM.js → coverage.CDRAMTt7.js} +25 -56
  11. package/dist/chunks/{globals.lgsmH00r.js → globals.CJrTTbxC.js} +5 -6
  12. package/dist/chunks/{index.C3EbxYwt.js → index.BIP7prJq.js} +7 -3
  13. package/dist/chunks/{index.D2B6d2vv.js → index.BjKEiSn0.js} +1 -1
  14. package/dist/chunks/{index.AR8aAkCC.js → index.C832ioot.js} +5 -6
  15. package/dist/chunks/{moduleRunner.d.CX4DuqOx.d.ts → moduleRunner.d.DxTLreRD.d.ts} +4 -1
  16. package/dist/chunks/{node.BOqcT2jW.js → node.CyipiPvJ.js} +1 -1
  17. package/dist/chunks/{plugin.d.vcD4xbMS.d.ts → plugin.d.CIk0YiKb.d.ts} +1 -1
  18. package/dist/chunks/{reporters.d.BC86JJdB.d.ts → reporters.d.DmP-iHLr.d.ts} +451 -561
  19. package/dist/chunks/{index.CsFXYRkW.js → resolveSnapshotEnvironment.Bvv2zr69.js} +16 -21
  20. package/dist/chunks/{rpc.RpPylpp0.js → rpc.BKr6mtxz.js} +1 -1
  21. package/dist/chunks/{setup-common.hLGRxhC8.js → setup-common.B7I37Tji.js} +4 -4
  22. package/dist/chunks/{startModuleRunner.C8TW8zTN.js → startModuleRunner.BDRvKSdz.js} +7 -2
  23. package/dist/chunks/test.BAlBebnP.js +214 -0
  24. package/dist/chunks/{typechecker.DSo_maXz.js → typechecker.DB-fIMaH.js} +44 -1
  25. package/dist/chunks/{utils.C7__0Iv5.js → utils.D2R2NiOH.js} +1 -10
  26. package/dist/chunks/{vi.BfdOiD4j.js → vi.BB37KeLx.js} +16 -16
  27. package/dist/chunks/{vm.BHBje7cC.js → vm.CjLTDaST.js} +12 -7
  28. package/dist/chunks/{worker.d.DYlqbejz.d.ts → worker.d.B2r4Ln6p.d.ts} +1 -1
  29. package/dist/chunks/{worker.d.BKu8cnnX.d.ts → worker.d.DJ6qxO2w.d.ts} +1 -1
  30. package/dist/cli.js +3 -3
  31. package/dist/config.d.ts +10 -10
  32. package/dist/coverage.d.ts +8 -8
  33. package/dist/coverage.js +2 -2
  34. package/dist/index.d.ts +11 -12
  35. package/dist/index.js +5 -8
  36. package/dist/module-evaluator.d.ts +4 -3
  37. package/dist/module-evaluator.js +3 -3
  38. package/dist/module-runner.js +2 -2
  39. package/dist/node.d.ts +23 -14
  40. package/dist/node.js +8 -8
  41. package/dist/reporters.d.ts +8 -8
  42. package/dist/reporters.js +3 -3
  43. package/dist/runners.d.ts +1 -1
  44. package/dist/runners.js +11 -215
  45. package/dist/snapshot.js +2 -2
  46. package/dist/suite.js +2 -2
  47. package/dist/worker.js +2 -3
  48. package/dist/workers/forks.js +27 -4
  49. package/dist/workers/runVmTests.js +18 -19
  50. package/dist/workers/threads.js +27 -4
  51. package/dist/workers/vmForks.js +4 -4
  52. package/dist/workers/vmThreads.js +4 -4
  53. package/dist/workers.d.ts +3 -3
  54. package/dist/workers.js +26 -8
  55. package/package.json +10 -14
  56. package/dist/chunks/base.BXI97p6t.js +0 -39
@@ -1,22 +1,22 @@
1
- import { Task, CancelReason, TaskMeta, Suite, File, TestAnnotation, ImportDuration, Test, TaskResultPack, SequenceSetupFiles, SequenceHooks } from '@vitest/runner';
2
- import { ParsedStack, Awaitable, TestError, SerializedError, Arrayable as Arrayable$1 } from '@vitest/utils';
1
+ import { CancelReason, TaskMeta, Suite, File, TestAnnotation, ImportDuration, Test, Task, TaskResultPack, SequenceSetupFiles, SequenceHooks } from '@vitest/runner';
2
+ import { Awaitable, ParsedStack, TestError, SerializedError, Arrayable as Arrayable$1 } from '@vitest/utils';
3
3
  import { P as ProvidedContext, c as Arrayable, A as AfterSuiteRunMeta, U as UserConsoleLog, b as Awaitable$1, L as LabelColor } from './environment.d.2fYMoz3o.js';
4
4
  import { Writable } from 'node:stream';
5
- import { ViteDevServer, ModuleNode, TransformResult as TransformResult$1, DepOptimizationConfig, ServerOptions, UserConfig as UserConfig$1, ConfigEnv, AliasOptions } from 'vite';
6
- import { Console } from 'node:console';
7
- import { B as BrowserTesterOptions, S as SerializedTestSpecification } from './browser.d.DOMmqJQx.js';
5
+ import { ViteDevServer, TransformResult as TransformResult$1, DepOptimizationConfig, ServerOptions, UserConfig as UserConfig$1, ConfigEnv, AliasOptions } from 'vite';
8
6
  import { MockedModule } from '@vitest/mocker';
9
7
  import { StackTraceParserOptions } from '@vitest/utils/source-map';
10
- import { a as SerializedConfig, F as FakeTimerInstallOpts } from './config.d._GBBbReY.js';
8
+ import { B as BrowserTesterOptions, S as SerializedTestSpecification } from './browser.d.DtfyY9yS.js';
9
+ import { a as SerializedConfig, F as FakeTimerInstallOpts } from './config.d.DacWrqWe.js';
11
10
  import { PrettyFormatOptions } from '@vitest/pretty-format';
12
11
  import { SnapshotSummary, SnapshotStateOptions } from '@vitest/snapshot';
13
12
  import { SerializedDiffOptions } from '@vitest/utils/diff';
14
- import * as chai from 'chai';
13
+ import { chai } from '@vitest/expect';
15
14
  import { happyDomTypes, jsdomTypes } from 'vitest/optional-types.js';
16
15
  import { B as BenchmarkResult } from './benchmark.d.DAaHLpsq.js';
17
16
  import { a as RuntimeCoverageProviderModule } from './coverage.d.BZtK59WP.js';
18
17
  import { SnapshotManager } from '@vitest/snapshot/manager';
19
18
  import { Stats } from 'node:fs';
19
+ import { Console } from 'node:console';
20
20
 
21
21
  type ChaiConfig = Omit<Partial<typeof chai.config>, "useProxy" | "proxyExcludedKeys">;
22
22
 
@@ -69,53 +69,6 @@ interface ConstructorOptionsOverride {
69
69
  resources?: "usable";
70
70
  }
71
71
 
72
- declare class TypeCheckError extends Error {
73
- message: string;
74
- stacks: ParsedStack[];
75
- name: string;
76
- constructor(message: string, stacks: ParsedStack[]);
77
- }
78
-
79
- interface ErrorOptions {
80
- type?: string;
81
- fullStack?: boolean;
82
- project?: TestProject;
83
- verbose?: boolean;
84
- screenshotPaths?: string[];
85
- task?: Task;
86
- showCodeFrame?: boolean;
87
- }
88
- type Listener = () => void;
89
- declare class Logger {
90
- ctx: Vitest;
91
- outputStream: NodeJS.WriteStream | Writable;
92
- errorStream: NodeJS.WriteStream | Writable;
93
- private _clearScreenPending;
94
- private _highlights;
95
- private cleanupListeners;
96
- console: Console;
97
- constructor(ctx: Vitest, outputStream?: NodeJS.WriteStream | Writable, errorStream?: NodeJS.WriteStream | Writable);
98
- log(...args: any[]): void;
99
- error(...args: any[]): void;
100
- warn(...args: any[]): void;
101
- clearFullScreen(message?: string): void;
102
- clearScreen(message: string, force?: boolean): void;
103
- private _clearScreen;
104
- printError(err: unknown, options?: ErrorOptions): void;
105
- deprecate(message: string): void;
106
- clearHighlightCache(filename?: string): void;
107
- highlight(filename: string, source: string): string;
108
- printNoTestFound(filters?: string[]): void;
109
- printBanner(): void;
110
- printBrowserBanner(project: TestProject): void;
111
- printUnhandledErrors(errors: ReadonlyArray<unknown>): void;
112
- printSourceTypeErrors(errors: TypeCheckError[]): void;
113
- getColumns(): number;
114
- onTerminalCleanup(listener: Listener): void;
115
- private addCleanupListeners;
116
- private registerUnhandledRejection;
117
- }
118
-
119
72
  interface BrowserProviderInitializationOptions {
120
73
  browser: string;
121
74
  options?: BrowserProviderOptions;
@@ -262,11 +215,6 @@ interface BrowserConfigOptions {
262
215
  */
263
216
  screenshotFailures?: boolean;
264
217
  /**
265
- * Scripts injected into the tester iframe.
266
- * @deprecated Will be removed in the future, use `testerHtmlPath` instead.
267
- */
268
- testerScripts?: BrowserScript[];
269
- /**
270
218
  * Path to the index.html file that will be used to run tests.
271
219
  */
272
220
  testerHtmlPath?: string;
@@ -472,660 +420,584 @@ interface ToMatchScreenshotOptions {
472
420
  }
473
421
  interface ToMatchScreenshotComparators {}
474
422
 
475
- declare class ReportedTaskImplementation {
476
- /**
477
- * The project associated with the test or suite.
478
- */
479
- readonly project: TestProject;
423
+ type BuiltinPool = "browser" | "threads" | "forks" | "vmThreads" | "vmForks" | "typescript";
424
+ type Pool = BuiltinPool | (string & {});
425
+ interface PoolOptions extends Record<string, unknown> {
480
426
  /**
481
- * Unique identifier.
482
- * This ID is deterministic and will be the same for the same test across multiple runs.
483
- * The ID is based on the project name, module url and test order.
427
+ * Run tests in `node:worker_threads`.
428
+ *
429
+ * Test isolation (when enabled) is done by spawning a new thread for each test file.
430
+ *
431
+ * This pool is used by default.
484
432
  */
485
- readonly id: string;
433
+ threads?: ThreadsOptions & WorkerContextOptions;
486
434
  /**
487
- * Location in the module where the test or suite is defined.
435
+ * Run tests in `node:child_process` using [`fork()`](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options)
436
+ *
437
+ * Test isolation (when enabled) is done by spawning a new child process for each test file.
488
438
  */
489
- readonly location: {
490
- line: number;
491
- column: number;
492
- } | undefined;
439
+ forks?: ForksOptions & WorkerContextOptions;
493
440
  /**
494
- * Checks if the test did not fail the suite.
495
- * If the test is not finished yet or was skipped, it will return `true`.
441
+ * Run tests in isolated `node:vm`.
442
+ * Test files are run parallel using `node:worker_threads`.
443
+ *
444
+ * This makes tests run faster, but VM module is unstable. Your tests might leak memory.
496
445
  */
497
- ok(): boolean;
446
+ vmThreads?: ThreadsOptions & VmOptions;
498
447
  /**
499
- * Custom metadata that was attached to the test during its execution.
448
+ * Run tests in isolated `node:vm`.
449
+ *
450
+ * Test files are run parallel using `node:child_process` [`fork()`](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options)
451
+ *
452
+ * This makes tests run faster, but VM module is unstable. Your tests might leak memory.
500
453
  */
501
- meta(): TaskMeta;
454
+ vmForks?: ForksOptions & VmOptions;
502
455
  }
503
- declare class TestCase extends ReportedTaskImplementation {
504
- #private;
505
- readonly type = "test";
506
- /**
507
- * Direct reference to the test module where the test or suite is defined.
508
- */
509
- readonly module: TestModule;
456
+ interface ResolvedPoolOptions extends PoolOptions {
457
+ threads?: ResolvedThreadsOptions & WorkerContextOptions;
458
+ forks?: ResolvedForksOptions & WorkerContextOptions;
459
+ vmThreads?: ResolvedThreadsOptions & VmOptions;
460
+ vmForks?: ResolvedForksOptions & VmOptions;
461
+ }
462
+ interface ThreadsOptions {
463
+ /** Maximum amount of threads to use */
464
+ maxThreads?: number | string;
510
465
  /**
511
- * Name of the test.
466
+ * Run tests inside a single thread.
467
+ *
468
+ * @default false
512
469
  */
513
- readonly name: string;
470
+ singleThread?: boolean;
514
471
  /**
515
- * Options that the test was initiated with.
472
+ * Use Atomics to synchronize threads
473
+ *
474
+ * This can improve performance in some cases, but might cause segfault in older Node versions.
475
+ *
476
+ * @default false
516
477
  */
517
- readonly options: TaskOptions;
478
+ useAtomics?: boolean;
479
+ }
480
+ interface ResolvedThreadsOptions extends ThreadsOptions {
481
+ maxThreads?: number;
482
+ }
483
+ interface ForksOptions {
484
+ /** Maximum amount of child processes to use */
485
+ maxForks?: number | string;
518
486
  /**
519
- * Parent suite. If the test was called directly inside the module, the parent will be the module itself.
487
+ * Run tests inside a single fork.
488
+ *
489
+ * @default false
520
490
  */
521
- readonly parent: TestSuite | TestModule;
491
+ singleFork?: boolean;
492
+ }
493
+ interface ResolvedForksOptions extends ForksOptions {
494
+ maxForks?: number;
495
+ }
496
+ interface WorkerContextOptions {
522
497
  /**
523
- * Full name of the test including all parent suites separated with `>`.
498
+ * Isolate test environment by recycling `worker_threads` or `child_process` after each test
499
+ *
500
+ * @default true
524
501
  */
525
- get fullName(): string;
502
+ isolate?: boolean;
526
503
  /**
527
- * Test results.
528
- * - **pending**: Test was collected, but didn't finish running yet.
529
- * - **passed**: Test passed successfully
530
- * - **failed**: Test failed to execute
531
- * - **skipped**: Test was skipped during collection or dynamically with `ctx.skip()`.
504
+ * Pass additional arguments to `node` process when spawning `worker_threads` or `child_process`.
505
+ *
506
+ * See [Command-line API | Node.js](https://nodejs.org/docs/latest/api/cli.html) for more information.
507
+ *
508
+ * Set to `process.execArgv` to pass all arguments of the current process.
509
+ *
510
+ * Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103
511
+ *
512
+ * @default [] // no execution arguments are passed
532
513
  */
533
- result(): TestResult;
514
+ execArgv?: string[];
515
+ }
516
+ interface VmOptions {
534
517
  /**
535
- * Test annotations added via the `task.annotate` API during the test execution.
518
+ * Specifies the memory limit for `worker_thread` or `child_process` before they are recycled.
519
+ * If you see memory leaks, try to tinker this value.
536
520
  */
537
- annotations(): ReadonlyArray<TestAnnotation>;
521
+ memoryLimit?: string | number;
522
+ /** Isolation is always enabled */
523
+ isolate?: true;
538
524
  /**
539
- * Useful information about the test like duration, memory usage, etc.
540
- * Diagnostic is only available after the test has finished.
525
+ * Pass additional arguments to `node` process when spawning `worker_threads` or `child_process`.
526
+ *
527
+ * See [Command-line API | Node.js](https://nodejs.org/docs/latest/api/cli.html) for more information.
528
+ *
529
+ * Set to `process.execArgv` to pass all arguments of the current process.
530
+ *
531
+ * Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103
532
+ *
533
+ * @default [] // no execution arguments are passed
541
534
  */
542
- diagnostic(): TestDiagnostic | undefined;
535
+ execArgv?: string[];
543
536
  }
544
- declare class TestCollection {
545
- #private;
546
- constructor(task: Suite | File, project: TestProject);
547
- /**
548
- * Returns the test or suite at a specific index.
549
- */
550
- at(index: number): TestCase | TestSuite | undefined;
537
+
538
+ declare class TestSpecification {
551
539
  /**
552
- * The number of tests and suites in the collection.
540
+ * The task ID associated with the test module.
553
541
  */
554
- get size(): number;
542
+ readonly taskId: string;
555
543
  /**
556
- * Returns the collection in array form for easier manipulation.
544
+ * The test project that the module belongs to.
557
545
  */
558
- array(): (TestCase | TestSuite)[];
546
+ readonly project: TestProject;
559
547
  /**
560
- * Filters all tests that are part of this collection and its children.
548
+ * The ID of the module in the Vite module graph. It is usually an absolute file path.
561
549
  */
562
- allTests(state?: TestState): Generator<TestCase, undefined, void>;
550
+ readonly moduleId: string;
563
551
  /**
564
- * Filters only the tests that are part of this collection.
552
+ * The current test pool. It's possible to have multiple pools in a single test project with `poolMatchGlob` and `typecheck.enabled`.
553
+ * @experimental In Vitest 4, the project will only support a single pool and this property will be removed.
565
554
  */
566
- tests(state?: TestState): Generator<TestCase, undefined, void>;
555
+ readonly pool: Pool;
567
556
  /**
568
- * Filters only the suites that are part of this collection.
557
+ * Line numbers of the test locations to run.
569
558
  */
570
- suites(): Generator<TestSuite, undefined, void>;
559
+ readonly testLines: number[] | undefined;
560
+ constructor(project: TestProject, moduleId: string, pool: Pool, testLines?: number[] | undefined);
571
561
  /**
572
- * Filters all suites that are part of this collection and its children.
562
+ * Test module associated with the specification.
573
563
  */
574
- allSuites(): Generator<TestSuite, undefined, void>;
575
- [Symbol.iterator](): Generator<TestSuite | TestCase, undefined, void>;
564
+ get testModule(): TestModule | undefined;
565
+ toJSON(): SerializedTestSpecification;
576
566
  }
577
567
 
578
- type ReportedHookContext = {
579
- readonly name: "beforeAll" | "afterAll";
580
- readonly entity: TestSuite | TestModule;
581
- } | {
582
- readonly name: "beforeEach" | "afterEach";
583
- readonly entity: TestCase;
584
- };
585
- declare abstract class SuiteImplementation extends ReportedTaskImplementation {
586
- /**
587
- * Collection of suites and tests that are part of this suite.
588
- */
589
- readonly children: TestCollection;
568
+ declare class TestProject {
569
+ options?: Vitest;
590
570
  /**
591
- * Errors that happened outside of the test run during collection, like syntax errors.
571
+ * The global Vitest instance.
572
+ * @experimental The public Vitest API is experimental and does not follow semver.
592
573
  */
593
- errors(): SerializedError[];
594
- }
595
- declare class TestSuite extends SuiteImplementation {
596
- #private;
597
- readonly type = "suite";
574
+ readonly vitest: Vitest;
598
575
  /**
599
- * Name of the test or the suite.
576
+ * Resolved global configuration. If there are no workspace projects, this will be the same as `config`.
600
577
  */
601
- readonly name: string;
578
+ readonly globalConfig: ResolvedConfig;
602
579
  /**
603
- * Direct reference to the test module where the test or suite is defined.
580
+ * Browser instance if the browser is enabled. This is initialized when the tests run for the first time.
604
581
  */
605
- readonly module: TestModule;
582
+ browser?: ProjectBrowser;
606
583
  /**
607
- * Parent suite. If suite was called directly inside the module, the parent will be the module itself.
584
+ * Temporary directory for the project. This is unique for each project. Vitest stores transformed content here.
608
585
  */
609
- readonly parent: TestSuite | TestModule;
586
+ readonly tmpDir: string;
587
+ /** @inetrnal */ testFilesList: string[] | null;
588
+ private runner;
589
+ private closingPromise;
590
+ private typecheckFilesList;
591
+ private _globalSetups?;
592
+ private _provided;
593
+ constructor(vitest: Vitest, options?: InitializeProjectOptions | undefined);
610
594
  /**
611
- * Options that suite was initiated with.
595
+ * The unique hash of this project. This value is consistent between the reruns.
596
+ *
597
+ * It is based on the root of the project (not consistent between OS) and its name.
612
598
  */
613
- readonly options: TaskOptions;
599
+ get hash(): string;
600
+ // "provide" is a property, not a method to keep the context when destructed in the global setup,
601
+ // making it a method would be a breaking change, and can be done in Vitest 3 at minimum
614
602
  /**
615
- * Checks if the suite has any failed tests.
616
- * This will also return `false` if suite failed during collection.
603
+ * Provide a value to the test context. This value will be available to all tests with `inject`.
617
604
  */
618
- ok: () => boolean;
605
+ provide: <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]) => void;
619
606
  /**
620
- * The meta information attached to the suite during its collection or execution.
607
+ * Get the provided context. The project context is merged with the global context.
621
608
  */
622
- meta: () => TaskMeta;
609
+ getProvidedContext(): ProvidedContext;
623
610
  /**
624
- * Checks the running state of the suite.
611
+ * Creates a new test specification. Specifications describe how to run tests.
612
+ * @param moduleId The file path
625
613
  */
626
- state(): TestSuiteState;
614
+ createSpecification(moduleId: string, locations?: number[] | undefined, pool?: string): TestSpecification;
615
+ toJSON(): SerializedTestProject;
627
616
  /**
628
- * Full name of the suite including all parent suites separated with `>`.
617
+ * Vite's dev server instance. Every workspace project has its own server.
629
618
  */
630
- get fullName(): string;
631
- }
632
- declare class TestModule extends SuiteImplementation {
633
- readonly location: undefined;
634
- readonly type = "module";
619
+ get vite(): ViteDevServer;
635
620
  /**
636
- * This is usually an absolute UNIX file path.
637
- * It can be a virtual ID if the file is not on the disk.
638
- * This value corresponds to the ID in the Vite's module graph.
621
+ * Resolved project configuration.
639
622
  */
640
- readonly moduleId: string;
623
+ get config(): ResolvedConfig;
641
624
  /**
642
- * Checks the running state of the test file.
625
+ * The name of the project or an empty string if not set.
643
626
  */
644
- state(): TestModuleState;
627
+ get name(): string;
645
628
  /**
646
- * Checks if the module has any failed tests.
647
- * This will also return `false` if module failed during collection.
629
+ * The color used when reporting tasks of this project.
648
630
  */
649
- ok: () => boolean;
631
+ get color(): ProjectName["color"];
650
632
  /**
651
- * The meta information attached to the module during its collection or execution.
633
+ * Serialized project configuration. This is the config that tests receive.
652
634
  */
653
- meta: () => TaskMeta;
635
+ get serializedConfig(): SerializedConfig;
654
636
  /**
655
- * Useful information about the module like duration, memory usage, etc.
656
- * If the module was not executed yet, all diagnostic values will return `0`.
637
+ * Check if this is the root project. The root project is the one that has the root config.
657
638
  */
658
- diagnostic(): ModuleDiagnostic;
659
- }
660
- interface TaskOptions {
661
- readonly each: boolean | undefined;
662
- readonly fails: boolean | undefined;
663
- readonly concurrent: boolean | undefined;
664
- readonly shuffle: boolean | undefined;
665
- readonly retry: number | undefined;
666
- readonly repeats: number | undefined;
667
- readonly mode: "run" | "only" | "skip" | "todo";
668
- }
669
- type TestSuiteState = "skipped" | "pending" | "failed" | "passed";
670
- type TestModuleState = TestSuiteState | "queued";
671
- type TestState = TestResult["state"];
672
- type TestResult = TestResultPassed | TestResultFailed | TestResultSkipped | TestResultPending;
673
- interface TestResultPending {
639
+ isRootProject(): boolean;
640
+ onTestsRerun(cb: OnTestsRerunHandler): void;
674
641
  /**
675
- * The test was collected, but didn't finish running yet.
642
+ * Get all files in the project that match the globs in the config and the filters.
643
+ * @param filters String filters to match the test files.
676
644
  */
677
- readonly state: "pending";
645
+ globTestFiles(filters?: string[]): Promise<{
646
+ /**
647
+ * Test files that match the filters.
648
+ */
649
+ testFiles: string[];
650
+ /**
651
+ * Typecheck test files that match the filters. This will be empty unless `typecheck.enabled` is `true`.
652
+ */
653
+ typecheckTestFiles: string[];
654
+ }>;
655
+ private globAllTestFiles;
656
+ isBrowserEnabled(): boolean;
657
+ private markTestFile;
678
658
  /**
679
- * Pending tests have no errors.
659
+ * Test if a file matches the test globs. This does the actual glob matching if the test is not cached, unlike `isCachedTestFile`.
680
660
  */
681
- readonly errors: undefined;
682
- }
683
- interface TestResultPassed {
661
+ matchesTestGlob(moduleId: string, source?: () => string): boolean;
662
+ private isInSourceTestCode;
663
+ private filterFiles;
664
+ private _parentBrowser?;
684
665
  /**
685
- * The test passed successfully.
666
+ * Closes the project and all associated resources. This can only be called once; the closing promise is cached until the server restarts.
667
+ * If the resources are needed again, create a new project.
686
668
  */
687
- readonly state: "passed";
669
+ close(): Promise<void>;
688
670
  /**
689
- * Errors that were thrown during the test execution.
690
- *
691
- * **Note**: If test was retried successfully, errors will still be reported.
671
+ * Import a file using Vite module runner.
672
+ * @param moduleId The ID of the module in Vite module graph
692
673
  */
693
- readonly errors: ReadonlyArray<TestError> | undefined;
674
+ import<T>(moduleId: string): Promise<T>;
675
+ private _setHash;
676
+ private _serializeOverriddenConfig;
677
+ private clearTmpDir;
694
678
  }
695
- interface TestResultFailed {
679
+ interface SerializedTestProject {
680
+ name: string;
681
+ serializedConfig: SerializedConfig;
682
+ context: ProvidedContext;
683
+ }
684
+ interface InitializeProjectOptions extends TestProjectInlineConfiguration {
685
+ configFile: string | false;
686
+ }
687
+
688
+ declare class ReportedTaskImplementation {
696
689
  /**
697
- * The test failed to execute.
690
+ * The project associated with the test or suite.
698
691
  */
699
- readonly state: "failed";
692
+ readonly project: TestProject;
700
693
  /**
701
- * Errors that were thrown during the test execution.
694
+ * Unique identifier.
695
+ * This ID is deterministic and will be the same for the same test across multiple runs.
696
+ * The ID is based on the project name, module url and test order.
702
697
  */
703
- readonly errors: ReadonlyArray<TestError>;
704
- }
705
- interface TestResultSkipped {
698
+ readonly id: string;
706
699
  /**
707
- * The test was skipped with `only` (on another test), `skip` or `todo` flag.
708
- * You can see which one was used in the `options.mode` option.
700
+ * Location in the module where the test or suite is defined.
709
701
  */
710
- readonly state: "skipped";
702
+ readonly location: {
703
+ line: number;
704
+ column: number;
705
+ } | undefined;
711
706
  /**
712
- * Skipped tests have no errors.
707
+ * Checks if the test did not fail the suite.
708
+ * If the test is not finished yet or was skipped, it will return `true`.
713
709
  */
714
- readonly errors: undefined;
710
+ ok(): boolean;
715
711
  /**
716
- * A custom note passed down to `ctx.skip(note)`.
712
+ * Custom metadata that was attached to the test during its execution.
717
713
  */
718
- readonly note: string | undefined;
714
+ meta(): TaskMeta;
719
715
  }
720
- interface TestDiagnostic {
716
+ declare class TestCase extends ReportedTaskImplementation {
717
+ #private;
718
+ readonly type = "test";
721
719
  /**
722
- * If the duration of the test is above `slowTestThreshold`.
720
+ * Direct reference to the test module where the test or suite is defined.
723
721
  */
724
- readonly slow: boolean;
722
+ readonly module: TestModule;
725
723
  /**
726
- * The amount of memory used by the test in bytes.
727
- * This value is only available if the test was executed with `logHeapUsage` flag.
724
+ * Name of the test.
728
725
  */
729
- readonly heap: number | undefined;
726
+ readonly name: string;
730
727
  /**
731
- * The time it takes to execute the test in ms.
728
+ * Options that the test was initiated with.
732
729
  */
733
- readonly duration: number;
730
+ readonly options: TaskOptions;
734
731
  /**
735
- * The time in ms when the test started.
732
+ * Parent suite. If the test was called directly inside the module, the parent will be the module itself.
736
733
  */
737
- readonly startTime: number;
734
+ readonly parent: TestSuite | TestModule;
738
735
  /**
739
- * The amount of times the test was retried.
736
+ * Full name of the test including all parent suites separated with `>`.
740
737
  */
741
- readonly retryCount: number;
738
+ get fullName(): string;
742
739
  /**
743
- * The amount of times the test was repeated as configured by `repeats` option.
744
- * This value can be lower if the test failed during the repeat and no `retry` is configured.
740
+ * Test results.
741
+ * - **pending**: Test was collected, but didn't finish running yet.
742
+ * - **passed**: Test passed successfully
743
+ * - **failed**: Test failed to execute
744
+ * - **skipped**: Test was skipped during collection or dynamically with `ctx.skip()`.
745
745
  */
746
- readonly repeatCount: number;
746
+ result(): TestResult;
747
747
  /**
748
- * If test passed on a second retry.
748
+ * Test annotations added via the `task.annotate` API during the test execution.
749
749
  */
750
- readonly flaky: boolean;
750
+ annotations(): ReadonlyArray<TestAnnotation>;
751
+ /**
752
+ * Useful information about the test like duration, memory usage, etc.
753
+ * Diagnostic is only available after the test has finished.
754
+ */
755
+ diagnostic(): TestDiagnostic | undefined;
751
756
  }
752
- interface ModuleDiagnostic {
757
+ declare class TestCollection {
758
+ #private;
759
+ constructor(task: Suite | File, project: TestProject);
753
760
  /**
754
- * The time it takes to import and initiate an environment.
761
+ * Returns the test or suite at a specific index.
755
762
  */
756
- readonly environmentSetupDuration: number;
763
+ at(index: number): TestCase | TestSuite | undefined;
757
764
  /**
758
- * The time it takes Vitest to setup test harness (runner, mocks, etc.).
765
+ * The number of tests and suites in the collection.
759
766
  */
760
- readonly prepareDuration: number;
767
+ get size(): number;
761
768
  /**
762
- * The time it takes to import the test module.
763
- * This includes importing everything in the module and executing suite callbacks.
769
+ * Returns the collection in array form for easier manipulation.
764
770
  */
765
- readonly collectDuration: number;
771
+ array(): (TestCase | TestSuite)[];
766
772
  /**
767
- * The time it takes to import the setup module.
773
+ * Filters all tests that are part of this collection and its children.
768
774
  */
769
- readonly setupDuration: number;
775
+ allTests(state?: TestState): Generator<TestCase, undefined, void>;
770
776
  /**
771
- * Accumulated duration of all tests and hooks in the module.
777
+ * Filters only the tests that are part of this collection.
772
778
  */
773
- readonly duration: number;
779
+ tests(state?: TestState): Generator<TestCase, undefined, void>;
774
780
  /**
775
- * The amount of memory used by the test module in bytes.
776
- * This value is only available if the test was executed with `logHeapUsage` flag.
781
+ * Filters only the suites that are part of this collection.
777
782
  */
778
- readonly heap: number | undefined;
783
+ suites(): Generator<TestSuite, undefined, void>;
779
784
  /**
780
- * The time spent importing every non-externalized dependency that Vitest has processed.
785
+ * Filters all suites that are part of this collection and its children.
781
786
  */
782
- readonly importDurations: Record<string, ImportDuration>;
787
+ allSuites(): Generator<TestSuite, undefined, void>;
788
+ [Symbol.iterator](): Generator<TestSuite | TestCase, undefined, void>;
783
789
  }
784
- declare function experimental_getRunnerTask(entity: TestCase): Test;
785
- declare function experimental_getRunnerTask(entity: TestSuite): Suite;
786
- declare function experimental_getRunnerTask(entity: TestModule): File;
787
- declare function experimental_getRunnerTask(entity: TestCase | TestSuite | TestModule): Suite | File | Test;
788
790
 
789
- type BuiltinPool = "browser" | "threads" | "forks" | "vmThreads" | "vmForks" | "typescript";
790
- type Pool = BuiltinPool | (string & {});
791
- interface PoolOptions extends Record<string, unknown> {
791
+ type ReportedHookContext = {
792
+ readonly name: "beforeAll" | "afterAll";
793
+ readonly entity: TestSuite | TestModule;
794
+ } | {
795
+ readonly name: "beforeEach" | "afterEach";
796
+ readonly entity: TestCase;
797
+ };
798
+ declare abstract class SuiteImplementation extends ReportedTaskImplementation {
792
799
  /**
793
- * Run tests in `node:worker_threads`.
794
- *
795
- * Test isolation (when enabled) is done by spawning a new thread for each test file.
796
- *
797
- * This pool is used by default.
800
+ * Collection of suites and tests that are part of this suite.
798
801
  */
799
- threads?: ThreadsOptions & WorkerContextOptions;
802
+ readonly children: TestCollection;
800
803
  /**
801
- * Run tests in `node:child_process` using [`fork()`](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options)
802
- *
803
- * Test isolation (when enabled) is done by spawning a new child process for each test file.
804
+ * Errors that happened outside of the test run during collection, like syntax errors.
804
805
  */
805
- forks?: ForksOptions & WorkerContextOptions;
806
+ errors(): SerializedError[];
807
+ }
808
+ declare class TestSuite extends SuiteImplementation {
809
+ #private;
810
+ readonly type = "suite";
806
811
  /**
807
- * Run tests in isolated `node:vm`.
808
- * Test files are run parallel using `node:worker_threads`.
809
- *
810
- * This makes tests run faster, but VM module is unstable. Your tests might leak memory.
812
+ * Name of the test or the suite.
811
813
  */
812
- vmThreads?: ThreadsOptions & VmOptions;
814
+ readonly name: string;
813
815
  /**
814
- * Run tests in isolated `node:vm`.
815
- *
816
- * Test files are run parallel using `node:child_process` [`fork()`](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options)
817
- *
818
- * This makes tests run faster, but VM module is unstable. Your tests might leak memory.
816
+ * Direct reference to the test module where the test or suite is defined.
819
817
  */
820
- vmForks?: ForksOptions & VmOptions;
821
- }
822
- interface ResolvedPoolOptions extends PoolOptions {
823
- threads?: ResolvedThreadsOptions & WorkerContextOptions;
824
- forks?: ResolvedForksOptions & WorkerContextOptions;
825
- vmThreads?: ResolvedThreadsOptions & VmOptions;
826
- vmForks?: ResolvedForksOptions & VmOptions;
827
- }
828
- interface ThreadsOptions {
829
- /** Minimum amount of threads to use */
830
- minThreads?: number | string;
831
- /** Maximum amount of threads to use */
832
- maxThreads?: number | string;
818
+ readonly module: TestModule;
833
819
  /**
834
- * Run tests inside a single thread.
835
- *
836
- * @default false
820
+ * Parent suite. If suite was called directly inside the module, the parent will be the module itself.
837
821
  */
838
- singleThread?: boolean;
822
+ readonly parent: TestSuite | TestModule;
839
823
  /**
840
- * Use Atomics to synchronize threads
841
- *
842
- * This can improve performance in some cases, but might cause segfault in older Node versions.
843
- *
844
- * @default false
824
+ * Options that suite was initiated with.
845
825
  */
846
- useAtomics?: boolean;
847
- }
848
- interface ResolvedThreadsOptions extends ThreadsOptions {
849
- minThreads?: number;
850
- maxThreads?: number;
851
- }
852
- interface ForksOptions {
853
- /** Minimum amount of child processes to use */
854
- minForks?: number | string;
855
- /** Maximum amount of child processes to use */
856
- maxForks?: number | string;
826
+ readonly options: TaskOptions;
857
827
  /**
858
- * Run tests inside a single fork.
859
- *
860
- * @default false
828
+ * Checks if the suite has any failed tests.
829
+ * This will also return `false` if suite failed during collection.
861
830
  */
862
- singleFork?: boolean;
863
- }
864
- interface ResolvedForksOptions extends ForksOptions {
865
- minForks?: number;
866
- maxForks?: number;
867
- }
868
- interface WorkerContextOptions {
831
+ ok: () => boolean;
869
832
  /**
870
- * Isolate test environment by recycling `worker_threads` or `child_process` after each test
871
- *
872
- * @default true
833
+ * The meta information attached to the suite during its collection or execution.
873
834
  */
874
- isolate?: boolean;
835
+ meta: () => TaskMeta;
875
836
  /**
876
- * Pass additional arguments to `node` process when spawning `worker_threads` or `child_process`.
877
- *
878
- * See [Command-line API | Node.js](https://nodejs.org/docs/latest/api/cli.html) for more information.
879
- *
880
- * Set to `process.execArgv` to pass all arguments of the current process.
881
- *
882
- * Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103
883
- *
884
- * @default [] // no execution arguments are passed
837
+ * Checks the running state of the suite.
885
838
  */
886
- execArgv?: string[];
887
- }
888
- interface VmOptions {
839
+ state(): TestSuiteState;
889
840
  /**
890
- * Specifies the memory limit for `worker_thread` or `child_process` before they are recycled.
891
- * If you see memory leaks, try to tinker this value.
841
+ * Full name of the suite including all parent suites separated with `>`.
892
842
  */
893
- memoryLimit?: string | number;
894
- /** Isolation is always enabled */
895
- isolate?: true;
843
+ get fullName(): string;
844
+ }
845
+ declare class TestModule extends SuiteImplementation {
846
+ readonly location: undefined;
847
+ readonly type = "module";
896
848
  /**
897
- * Pass additional arguments to `node` process when spawning `worker_threads` or `child_process`.
898
- *
899
- * See [Command-line API | Node.js](https://nodejs.org/docs/latest/api/cli.html) for more information.
900
- *
901
- * Set to `process.execArgv` to pass all arguments of the current process.
902
- *
903
- * Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103
904
- *
905
- * @default [] // no execution arguments are passed
849
+ * This is usually an absolute UNIX file path.
850
+ * It can be a virtual ID if the file is not on the disk.
851
+ * This value corresponds to the ID in the Vite's module graph.
906
852
  */
907
- execArgv?: string[];
908
- }
909
-
910
- declare class TestSpecification {
853
+ readonly moduleId: string;
911
854
  /**
912
- * @deprecated use `project` instead
855
+ * Checks the running state of the test file.
913
856
  */
914
- readonly 0: TestProject;
857
+ state(): TestModuleState;
915
858
  /**
916
- * @deprecated use `moduleId` instead
859
+ * Checks if the module has any failed tests.
860
+ * This will also return `false` if module failed during collection.
917
861
  */
918
- readonly 1: string;
862
+ ok: () => boolean;
919
863
  /**
920
- * @deprecated use `pool` instead
864
+ * The meta information attached to the module during its collection or execution.
921
865
  */
922
- readonly 2: {
923
- pool: Pool;
924
- };
866
+ meta: () => TaskMeta;
925
867
  /**
926
- * The task ID associated with the test module.
868
+ * Useful information about the module like duration, memory usage, etc.
869
+ * If the module was not executed yet, all diagnostic values will return `0`.
927
870
  */
928
- readonly taskId: string;
871
+ diagnostic(): ModuleDiagnostic;
872
+ }
873
+ interface TaskOptions {
874
+ readonly each: boolean | undefined;
875
+ readonly fails: boolean | undefined;
876
+ readonly concurrent: boolean | undefined;
877
+ readonly shuffle: boolean | undefined;
878
+ readonly retry: number | undefined;
879
+ readonly repeats: number | undefined;
880
+ readonly mode: "run" | "only" | "skip" | "todo";
881
+ }
882
+ type TestSuiteState = "skipped" | "pending" | "failed" | "passed";
883
+ type TestModuleState = TestSuiteState | "queued";
884
+ type TestState = TestResult["state"];
885
+ type TestResult = TestResultPassed | TestResultFailed | TestResultSkipped | TestResultPending;
886
+ interface TestResultPending {
929
887
  /**
930
- * The test project that the module belongs to.
888
+ * The test was collected, but didn't finish running yet.
931
889
  */
932
- readonly project: TestProject;
890
+ readonly state: "pending";
933
891
  /**
934
- * The ID of the module in the Vite module graph. It is usually an absolute file path.
892
+ * Pending tests have no errors.
935
893
  */
936
- readonly moduleId: string;
894
+ readonly errors: undefined;
895
+ }
896
+ interface TestResultPassed {
937
897
  /**
938
- * The current test pool. It's possible to have multiple pools in a single test project with `poolMatchGlob` and `typecheck.enabled`.
939
- * @experimental In Vitest 4, the project will only support a single pool and this property will be removed.
898
+ * The test passed successfully.
940
899
  */
941
- readonly pool: Pool;
900
+ readonly state: "passed";
942
901
  /**
943
- * Line numbers of the test locations to run.
902
+ * Errors that were thrown during the test execution.
903
+ *
904
+ * **Note**: If test was retried successfully, errors will still be reported.
944
905
  */
945
- readonly testLines: number[] | undefined;
946
- constructor(project: TestProject, moduleId: string, pool: Pool, testLines?: number[] | undefined);
906
+ readonly errors: ReadonlyArray<TestError> | undefined;
907
+ }
908
+ interface TestResultFailed {
947
909
  /**
948
- * Test module associated with the specification.
910
+ * The test failed to execute.
949
911
  */
950
- get testModule(): TestModule | undefined;
951
- toJSON(): SerializedTestSpecification;
912
+ readonly state: "failed";
952
913
  /**
953
- * for backwards compatibility
954
- * @deprecated
914
+ * Errors that were thrown during the test execution.
955
915
  */
956
- [Symbol.iterator](): Generator<string | TestProject, void, unknown>;
916
+ readonly errors: ReadonlyArray<TestError>;
957
917
  }
958
-
959
- declare class TestProject {
960
- /** @deprecated */
961
- path: string | number;
962
- options?: Vitest;
963
- /**
964
- * The global Vitest instance.
965
- * @experimental The public Vitest API is experimental and does not follow semver.
966
- */
967
- readonly vitest: Vitest;
918
+ interface TestResultSkipped {
968
919
  /**
969
- * Resolved global configuration. If there are no workspace projects, this will be the same as `config`.
920
+ * The test was skipped with `only` (on another test), `skip` or `todo` flag.
921
+ * You can see which one was used in the `options.mode` option.
970
922
  */
971
- readonly globalConfig: ResolvedConfig;
923
+ readonly state: "skipped";
972
924
  /**
973
- * Browser instance if the browser is enabled. This is initialized when the tests run for the first time.
925
+ * Skipped tests have no errors.
974
926
  */
975
- browser?: ProjectBrowser;
976
- /** @deprecated use `vitest` instead */
977
- ctx: Vitest;
927
+ readonly errors: undefined;
978
928
  /**
979
- * Temporary directory for the project. This is unique for each project. Vitest stores transformed content here.
929
+ * A custom note passed down to `ctx.skip(note)`.
980
930
  */
981
- readonly tmpDir: string;
982
- /** @inetrnal */ testFilesList: string[] | null;
983
- private runner;
984
- private closingPromise;
985
- private typecheckFilesList;
986
- private _globalSetups?;
987
- private _provided;
988
- constructor(path: string | number, vitest: Vitest, options?: InitializeProjectOptions | undefined);
931
+ readonly note: string | undefined;
932
+ }
933
+ interface TestDiagnostic {
989
934
  /**
990
- * The unique hash of this project. This value is consistent between the reruns.
991
- *
992
- * It is based on the root of the project (not consistent between OS) and its name.
935
+ * If the duration of the test is above `slowTestThreshold`.
993
936
  */
994
- get hash(): string;
995
- // "provide" is a property, not a method to keep the context when destructed in the global setup,
996
- // making it a method would be a breaking change, and can be done in Vitest 3 at minimum
937
+ readonly slow: boolean;
997
938
  /**
998
- * Provide a value to the test context. This value will be available to all tests with `inject`.
939
+ * The amount of memory used by the test in bytes.
940
+ * This value is only available if the test was executed with `logHeapUsage` flag.
999
941
  */
1000
- provide: <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]) => void;
942
+ readonly heap: number | undefined;
1001
943
  /**
1002
- * Get the provided context. The project context is merged with the global context.
944
+ * The time it takes to execute the test in ms.
1003
945
  */
1004
- getProvidedContext(): ProvidedContext;
946
+ readonly duration: number;
1005
947
  /**
1006
- * Creates a new test specification. Specifications describe how to run tests.
1007
- * @param moduleId The file path
948
+ * The time in ms when the test started.
1008
949
  */
1009
- createSpecification(moduleId: string, locations?: number[] | undefined, pool?: string): TestSpecification;
1010
- toJSON(): SerializedTestProject;
950
+ readonly startTime: number;
1011
951
  /**
1012
- * Vite's dev server instance. Every workspace project has its own server.
952
+ * The amount of times the test was retried.
1013
953
  */
1014
- get vite(): ViteDevServer;
954
+ readonly retryCount: number;
1015
955
  /**
1016
- * Resolved project configuration.
956
+ * The amount of times the test was repeated as configured by `repeats` option.
957
+ * This value can be lower if the test failed during the repeat and no `retry` is configured.
1017
958
  */
1018
- get config(): ResolvedConfig;
959
+ readonly repeatCount: number;
1019
960
  /**
1020
- * The name of the project or an empty string if not set.
961
+ * If test passed on a second retry.
1021
962
  */
1022
- get name(): string;
963
+ readonly flaky: boolean;
964
+ }
965
+ interface ModuleDiagnostic {
1023
966
  /**
1024
- * The color used when reporting tasks of this project.
967
+ * The time it takes to import and initiate an environment.
1025
968
  */
1026
- get color(): ProjectName["color"];
969
+ readonly environmentSetupDuration: number;
1027
970
  /**
1028
- * Serialized project configuration. This is the config that tests receive.
971
+ * The time it takes Vitest to setup test harness (runner, mocks, etc.).
1029
972
  */
1030
- get serializedConfig(): SerializedConfig;
1031
- /** @deprecated use `vite` instead */
1032
- get server(): ViteDevServer;
973
+ readonly prepareDuration: number;
1033
974
  /**
1034
- * Check if this is the root project. The root project is the one that has the root config.
975
+ * The time it takes to import the test module.
976
+ * This includes importing everything in the module and executing suite callbacks.
1035
977
  */
1036
- isRootProject(): boolean;
1037
- /** @deprecated use `isRootProject` instead */
1038
- isCore(): boolean;
1039
- /** @deprecated use `createSpecification` instead */
1040
- createSpec(moduleId: string, pool: string): WorkspaceSpec;
1041
- /** @deprecated */
1042
- initializeGlobalSetup(): Promise<void>;
1043
- onTestsRerun(cb: OnTestsRerunHandler): void;
1044
- /** @deprecated */
1045
- teardownGlobalSetup(): Promise<void>;
1046
- /** @deprecated use `vitest.logger` instead */
1047
- get logger(): Logger;
1048
- // it's possible that file path was imported with different queries (?raw, ?url, etc)
1049
- /** @deprecated use `.vite` or `.browser.vite` directly */
1050
- getModulesByFilepath(file: string): Set<ModuleNode>;
1051
- /** @deprecated use `.vite` or `.browser.vite` directly */
1052
- getModuleById(id: string): ModuleNode | undefined;
1053
- /** @deprecated use `.vite` or `.browser.vite` directly */
1054
- getSourceMapModuleById(id: string): TransformResult$1["map"] | undefined;
1055
- /** @deprecated use `vitest.reporters` instead */
1056
- get reporters(): Reporter[];
978
+ readonly collectDuration: number;
1057
979
  /**
1058
- * Get all files in the project that match the globs in the config and the filters.
1059
- * @param filters String filters to match the test files.
980
+ * The time it takes to import the setup module.
1060
981
  */
1061
- globTestFiles(filters?: string[]): Promise<{
1062
- /**
1063
- * Test files that match the filters.
1064
- */
1065
- testFiles: string[];
1066
- /**
1067
- * Typecheck test files that match the filters. This will be empty unless `typecheck.enabled` is `true`.
1068
- */
1069
- typecheckTestFiles: string[];
1070
- }>;
1071
- private globAllTestFiles;
1072
- isBrowserEnabled(): boolean;
1073
- private markTestFile;
1074
- /** @deprecated use `serializedConfig` instead */
1075
- getSerializableConfig(): SerializedConfig;
982
+ readonly setupDuration: number;
1076
983
  /**
1077
- * Test if a file matches the test globs. This does the actual glob matching if the test is not cached, unlike `isCachedTestFile`.
984
+ * Accumulated duration of all tests and hooks in the module.
1078
985
  */
1079
- matchesTestGlob(moduleId: string, source?: () => string): boolean;
1080
- /** @deprecated use `matchesTestGlob` instead */
1081
- isTargetFile(id: string, source?: string): Promise<boolean>;
1082
- private isInSourceTestCode;
1083
- private filterFiles;
1084
- private _parentBrowser?;
986
+ readonly duration: number;
1085
987
  /**
1086
- * Closes the project and all associated resources. This can only be called once; the closing promise is cached until the server restarts.
1087
- * If the resources are needed again, create a new project.
988
+ * The amount of memory used by the test module in bytes.
989
+ * This value is only available if the test was executed with `logHeapUsage` flag.
1088
990
  */
1089
- close(): Promise<void>;
991
+ readonly heap: number | undefined;
1090
992
  /**
1091
- * Import a file using Vite module runner.
1092
- * @param moduleId The ID of the module in Vite module graph
993
+ * The time spent importing every non-externalized dependency that Vitest has processed.
1093
994
  */
1094
- import<T>(moduleId: string): Promise<T>;
1095
- /** @deprecated use `name` instead */
1096
- getName(): string;
1097
- /** @deprecated internal */
1098
- setServer(options: UserConfig, server: ViteDevServer): Promise<void>;
1099
- private _setHash;
1100
- private _serializeOverriddenConfig;
1101
- private clearTmpDir;
1102
- /** @deprecated */
1103
- initBrowserProvider(): Promise<void>;
1104
- }
1105
-
1106
- interface SerializedTestProject {
1107
- name: string;
1108
- serializedConfig: SerializedConfig;
1109
- context: ProvidedContext;
1110
- }
1111
- interface InitializeProjectOptions extends TestProjectInlineConfiguration {
1112
- configFile: string | false;
1113
- }
1114
-
1115
- /**
1116
- * @deprecated use TestSpecification instead
1117
- */
1118
- type WorkspaceSpec = TestSpecification & [project: TestProject, file: string, options: {
1119
- pool: Pool;
1120
- }];
1121
- type RunWithFiles = (files: TestSpecification[], invalidates?: string[]) => Awaitable<void>;
1122
- interface ProcessPool {
1123
- name: string;
1124
- runTests: RunWithFiles;
1125
- collectTests: RunWithFiles;
1126
- close?: () => Awaitable<void>;
995
+ readonly importDurations: Record<string, ImportDuration>;
1127
996
  }
1128
- declare function getFilePoolName(project: TestProject): Pool;
997
+ declare function experimental_getRunnerTask(entity: TestCase): Test;
998
+ declare function experimental_getRunnerTask(entity: TestSuite): Suite;
999
+ declare function experimental_getRunnerTask(entity: TestModule): File;
1000
+ declare function experimental_getRunnerTask(entity: TestCase | TestSuite | TestModule): Suite | File | Test;
1129
1001
 
1130
1002
  interface CoverageSummaryData {
1131
1003
  lines: Totals;
@@ -1328,6 +1200,8 @@ interface CoverageProvider {
1328
1200
  mergeReports?: (coverages: CoverageResults[]) => void | Promise<void>;
1329
1201
  /** Callback called for instrumenting files with coverage counters. */
1330
1202
  onFileTransform?: (sourceCode: string, id: string, pluginCtx: any) => TransformResult | Promise<TransformResult>;
1203
+ /** Callback that's called when the coverage is enabled via a programmatic `enableCoverage` API. */
1204
+ onEnabled?: () => void | Promise<void>;
1331
1205
  }
1332
1206
  interface ReportContext {
1333
1207
  /** Indicates whether all tests were run. False when only specific tests were run. */
@@ -1555,6 +1429,53 @@ declare class VitestCache {
1555
1429
  static resolveCacheDir(root: string, dir?: string, projectName?: string): string;
1556
1430
  }
1557
1431
 
1432
+ declare class TypeCheckError extends Error {
1433
+ message: string;
1434
+ stacks: ParsedStack[];
1435
+ name: string;
1436
+ constructor(message: string, stacks: ParsedStack[]);
1437
+ }
1438
+
1439
+ interface ErrorOptions {
1440
+ type?: string;
1441
+ fullStack?: boolean;
1442
+ project?: TestProject;
1443
+ verbose?: boolean;
1444
+ screenshotPaths?: string[];
1445
+ task?: Task;
1446
+ showCodeFrame?: boolean;
1447
+ }
1448
+ type Listener = () => void;
1449
+ declare class Logger {
1450
+ ctx: Vitest;
1451
+ outputStream: NodeJS.WriteStream | Writable;
1452
+ errorStream: NodeJS.WriteStream | Writable;
1453
+ private _clearScreenPending;
1454
+ private _highlights;
1455
+ private cleanupListeners;
1456
+ console: Console;
1457
+ constructor(ctx: Vitest, outputStream?: NodeJS.WriteStream | Writable, errorStream?: NodeJS.WriteStream | Writable);
1458
+ log(...args: any[]): void;
1459
+ error(...args: any[]): void;
1460
+ warn(...args: any[]): void;
1461
+ clearFullScreen(message?: string): void;
1462
+ clearScreen(message: string, force?: boolean): void;
1463
+ private _clearScreen;
1464
+ printError(err: unknown, options?: ErrorOptions): void;
1465
+ deprecate(message: string): void;
1466
+ clearHighlightCache(filename?: string): void;
1467
+ highlight(filename: string, source: string): string;
1468
+ printNoTestFound(filters?: string[]): void;
1469
+ printBanner(): void;
1470
+ printBrowserBanner(project: TestProject): void;
1471
+ printUnhandledErrors(errors: ReadonlyArray<unknown>): void;
1472
+ printSourceTypeErrors(errors: TypeCheckError[]): void;
1473
+ getColumns(): number;
1474
+ onTerminalCleanup(listener: Listener): void;
1475
+ private addCleanupListeners;
1476
+ private registerUnhandledRejection;
1477
+ }
1478
+
1558
1479
  declare class VitestPackageInstaller {
1559
1480
  isPackageExists(name: string, options?: {
1560
1481
  paths?: string[];
@@ -1705,6 +1626,7 @@ declare class Vitest {
1705
1626
  private _state?;
1706
1627
  private _cache?;
1707
1628
  private _snapshot?;
1629
+ private _coverageProvider?;
1708
1630
  constructor(mode: VitestRunMode, cliOptions: UserConfig, options?: VitestOptions);
1709
1631
  private _onRestartListeners;
1710
1632
  private _onClose;
@@ -1712,16 +1634,10 @@ declare class Vitest {
1712
1634
  private _onCancelListeners;
1713
1635
  private _onUserTestsRerun;
1714
1636
  private _onFilterWatchedSpecification;
1715
- /** @deprecated will be removed in 4.0, use `onFilterWatchedSpecification` instead */
1716
- get invalidates(): Set<string>;
1717
- /** @deprecated will be removed in 4.0, use `onFilterWatchedSpecification` instead */
1718
- get changedTests(): Set<string>;
1719
1637
  /**
1720
1638
  * The global config.
1721
1639
  */
1722
1640
  get config(): ResolvedConfig;
1723
- /** @deprecated use `vitest.vite` instead */
1724
- get server(): ViteDevServer;
1725
1641
  /**
1726
1642
  * Global Vite's dev server instance.
1727
1643
  */
@@ -1739,8 +1655,9 @@ declare class Vitest {
1739
1655
  * Test results and test file stats cache. Primarily used by the sequencer to sort tests.
1740
1656
  */
1741
1657
  get cache(): VitestCache;
1742
- /** @deprecated internal */
1743
- setServer(options: UserConfig, server: ViteDevServer): Promise<void>;
1658
+ enableCoverage(): Promise<void>;
1659
+ disableCoverage(): void;
1660
+ private _coverageOverrideCache;
1744
1661
  /**
1745
1662
  * Inject new test projects into the workspace.
1746
1663
  * @param config Glob, config path or a custom config options.
@@ -1755,16 +1672,10 @@ declare class Vitest {
1755
1672
  * Get global provided context.
1756
1673
  */
1757
1674
  getProvidedContext(): ProvidedContext;
1758
- /** @deprecated use `getRootProject` instead */
1759
- getCoreWorkspaceProject(): TestProject;
1760
1675
  /**
1761
1676
  * Return project that has the root (or "global") config.
1762
1677
  */
1763
1678
  getRootProject(): TestProject;
1764
- /**
1765
- * @deprecated use Reported Task API instead
1766
- */
1767
- getProjectByTaskId(taskId: string): TestProject;
1768
1679
  getProjectByName(name: string): TestProject;
1769
1680
  /**
1770
1681
  * Import a file using Vite module runner. The file will be transformed by Vite and executed in a separate context.
@@ -1787,8 +1698,6 @@ declare class Vitest {
1787
1698
  */
1788
1699
  mergeReports(directory?: string): Promise<TestRunResult>;
1789
1700
  collect(filters?: string[]): Promise<TestRunResult>;
1790
- /** @deprecated use `getRelevantTestSpecifications` instead */
1791
- listFiles(filters?: string[]): Promise<TestSpecification[]>;
1792
1701
  /**
1793
1702
  * Returns the list of test files that match the config and filters.
1794
1703
  * @param filters String filters to match the test files
@@ -1809,12 +1718,6 @@ declare class Vitest {
1809
1718
  */
1810
1719
  init(): Promise<void>;
1811
1720
  /**
1812
- * @deprecated remove when vscode extension supports "getModuleSpecifications"
1813
- */
1814
- getProjectsByTestFile(file: string): WorkspaceSpec[];
1815
- /** @deprecated */
1816
- getFileWorkspaceSpecs(file: string): WorkspaceSpec[];
1817
- /**
1818
1721
  * If there is a test run happening, returns a promise that will
1819
1722
  * resolve when the test run is finished.
1820
1723
  */
@@ -1881,6 +1784,10 @@ declare class Vitest {
1881
1784
  */
1882
1785
  setGlobalTestNamePattern(pattern: string | RegExp): void;
1883
1786
  /**
1787
+ * Returns the regexp used for the global test name pattern.
1788
+ */
1789
+ getGlobalTestNamePattern(): RegExp | undefined;
1790
+ /**
1884
1791
  * Resets the global test name pattern. This method doesn't run any tests.
1885
1792
  */
1886
1793
  resetGlobalTestNamePattern(): void;
@@ -1890,8 +1797,6 @@ declare class Vitest {
1890
1797
  * Invalidate a file in all projects.
1891
1798
  */
1892
1799
  invalidateFile(filepath: string): void;
1893
- /** @deprecated use `invalidateFile` */
1894
- updateLastChanged(filepath: string): void;
1895
1800
  private reportCoverage;
1896
1801
  /**
1897
1802
  * Closes all projects and their associated resources.
@@ -1904,16 +1809,6 @@ declare class Vitest {
1904
1809
  */
1905
1810
  exit(force?: boolean): Promise<void>;
1906
1811
  /**
1907
- * @deprecated use `globTestSpecifications` instead
1908
- */
1909
- globTestSpecs(filters?: string[]): Promise<TestSpecification[]>;
1910
- /**
1911
- * @deprecated use `globTestSpecifications` instead
1912
- */
1913
- globTestFiles(filters?: string[]): Promise<TestSpecification[]>;
1914
- /** @deprecated filter by `this.projects` yourself */
1915
- getModuleProjects(filepath: string): TestProject[];
1916
- /**
1917
1812
  * Should the server be kept running after the tests are done.
1918
1813
  */
1919
1814
  shouldKeepServer(): boolean;
@@ -2598,12 +2493,8 @@ interface InlineConfig {
2598
2493
  */
2599
2494
  maxWorkers?: number | string;
2600
2495
  /**
2601
- * Minimum number or percentage of workers to run tests in. `poolOptions.{threads,vmThreads}.minThreads`/`poolOptions.forks.minForks` has higher priority.
2602
- */
2603
- minWorkers?: number | string;
2604
- /**
2605
2496
  * Should all test files run in parallel. Doesn't affect tests running in the same file.
2606
- * Setting this to `false` will override `maxWorkers` and `minWorkers` options to `1`.
2497
+ * Setting this to `false` will override `maxWorkers` option to `1`.
2607
2498
  *
2608
2499
  * @default true
2609
2500
  */
@@ -3176,9 +3067,8 @@ interface ResolvedConfig extends Omit<Required<UserConfig>, "project" | "config"
3176
3067
  };
3177
3068
  runner?: string;
3178
3069
  maxWorkers: number;
3179
- minWorkers: number;
3180
3070
  }
3181
- type NonProjectOptions = "shard" | "watch" | "run" | "cache" | "update" | "reporters" | "outputFile" | "teardownTimeout" | "silent" | "forceRerunTriggers" | "testNamePattern" | "ui" | "open" | "uiBase" | "snapshotFormat" | "resolveSnapshotPath" | "passWithNoTests" | "onConsoleLog" | "onStackTrace" | "dangerouslyIgnoreUnhandledErrors" | "slowTestThreshold" | "inspect" | "inspectBrk" | "coverage" | "maxWorkers" | "minWorkers" | "fileParallelism" | "watchTriggerPatterns";
3071
+ type NonProjectOptions = "shard" | "watch" | "run" | "cache" | "update" | "reporters" | "outputFile" | "teardownTimeout" | "silent" | "forceRerunTriggers" | "testNamePattern" | "ui" | "open" | "uiBase" | "snapshotFormat" | "resolveSnapshotPath" | "passWithNoTests" | "onConsoleLog" | "onStackTrace" | "dangerouslyIgnoreUnhandledErrors" | "slowTestThreshold" | "inspect" | "inspectBrk" | "coverage" | "maxWorkers" | "fileParallelism" | "watchTriggerPatterns";
3182
3072
  interface ServerDepsOptions {
3183
3073
  /**
3184
3074
  * Externalize means that Vite will bpass the package to native Node.
@@ -3230,5 +3120,5 @@ type TestProjectInlineConfiguration = (UserWorkspaceConfig & {
3230
3120
  });
3231
3121
  type TestProjectConfiguration = string | TestProjectInlineConfiguration | Promise<UserWorkspaceConfig> | UserProjectConfigFn;
3232
3122
 
3233
- export { CoverageMap as C, TestSuite as E, experimental_getRunnerTask as G, Logger as L, TestProject as T, Vitest as V, BenchmarkReporter as aB, BenchmarkReportsMap as aC, DefaultReporter as aD, DotReporter as aE, GithubActionsReporter as aF, HangingProcessReporter as aG, JsonReporter as aH, JUnitReporter as aI, ReportersMap as aJ, TapFlatReporter as aK, TapReporter as aL, VerboseBenchmarkReporter as aM, VerboseReporter as aN, BaseReporter as aO, TestSpecification as l, VitestPackageInstaller as n, getFilePoolName as p, TestCase as s, TestCollection as t, TestModule as v };
3234
- export type { BrowserModuleMocker as $, ApiConfig as A, TestResultSkipped as B, TestState as D, TestSuiteState as F, HTMLOptions as H, InlineConfig as I, JsonOptions as J, TestSequencerConstructor as K, ModuleDiagnostic as M, BenchmarkUserOptions as N, OnServerRestartHandler as O, ProcessPool as P, BrowserBuiltinProvider as Q, ResolvedCoverageOptions as R, SerializedTestProject as S, UserWorkspaceConfig as U, WatcherTriggerPattern as W, BrowserCommand as X, BrowserCommandContext as Y, BrowserConfigOptions as Z, BrowserInstanceOption as _, TestProjectConfiguration as a, BrowserOrchestrator as a0, BrowserProvider as a1, BrowserProviderInitializationOptions as a2, BrowserProviderModule as a3, BrowserProviderOptions as a4, BrowserScript as a5, BrowserServerState as a6, BrowserServerStateSession as a7, CDPSession as a8, ParentProjectBrowser as a9, TestRunEndReason as aA, BenchmarkBuiltinReporters as aP, BuiltinReporterOptions as aQ, BuiltinReporters as aR, JsonAssertionResult as aS, JsonTestResult as aT, JsonTestResults as aU, ProjectBrowser as aa, ResolvedBrowserOptions as ab, ToMatchScreenshotComparators as ac, ToMatchScreenshotOptions as ad, BuiltinEnvironment as ae, CSSModuleScopeStrategy as af, DepsOptimizationOptions as ag, EnvironmentOptions as ah, Pool as ai, PoolOptions as aj, ProjectConfig as ak, ResolvedProjectConfig as al, ResolveSnapshotPathHandler as am, ResolveSnapshotPathHandlerContext as an, TypecheckConfig as ao, VitestEnvironment as ap, BaseCoverageOptions as aq, CoverageIstanbulOptions as ar, CoverageOptions as as, CoverageProvider as at, CoverageProviderModule as au, CoverageReporter as av, CustomProviderOptions as aw, TestRunResult as ax, ReportedHookContext as ay, Reporter as az, ReportContext as b, CoverageV8Options as c, UserProjectConfigFn as d, UserProjectConfigExport as e, UserConfig as f, TestProjectInlineConfiguration as g, ResolvedConfig as h, VitestRunMode as i, VitestOptions as j, TestSequencer as k, OnTestsRerunHandler as m, WorkspaceSpec as o, JUnitOptions as q, TaskOptions as r, TestDiagnostic as u, TestModuleState as w, TestResult as x, TestResultFailed as y, TestResultPassed as z };
3123
+ export { TestSuite as B, CoverageMap as C, experimental_getRunnerTask as E, Logger as L, TestProject as T, Vitest as V, DefaultReporter as aA, DotReporter as aB, GithubActionsReporter as aC, HangingProcessReporter as aD, JsonReporter as aE, JUnitReporter as aF, ReportersMap as aG, TapFlatReporter as aH, TapReporter as aI, VerboseBenchmarkReporter as aJ, VerboseReporter as aK, BaseReporter as aL, BenchmarkReporter as ay, BenchmarkReportsMap as az, TestSpecification as k, VitestPackageInstaller as n, TestCase as q, TestCollection as r, TestModule as t };
3124
+ export type { BrowserProvider as $, ApiConfig as A, TestSuiteState as D, TestSequencerConstructor as F, BenchmarkUserOptions as G, HTMLOptions as H, InlineConfig as I, JsonOptions as J, BrowserBuiltinProvider as K, ModuleDiagnostic as M, BrowserCommand as N, OnServerRestartHandler as O, Pool as P, BrowserCommandContext as Q, ResolvedCoverageOptions as R, SerializedTestProject as S, UserWorkspaceConfig as U, WatcherTriggerPattern as W, BrowserConfigOptions as X, BrowserInstanceOption as Y, BrowserModuleMocker as Z, BrowserOrchestrator as _, TestProjectConfiguration as a, BrowserProviderInitializationOptions as a0, BrowserProviderModule as a1, BrowserProviderOptions as a2, BrowserScript as a3, BrowserServerState as a4, BrowserServerStateSession as a5, CDPSession as a6, ParentProjectBrowser as a7, ProjectBrowser as a8, ResolvedBrowserOptions as a9, BenchmarkBuiltinReporters as aM, BuiltinReporterOptions as aN, BuiltinReporters as aO, JsonAssertionResult as aP, JsonTestResult as aQ, JsonTestResults as aR, ToMatchScreenshotComparators as aa, ToMatchScreenshotOptions as ab, BuiltinEnvironment as ac, CSSModuleScopeStrategy as ad, DepsOptimizationOptions as ae, EnvironmentOptions as af, PoolOptions as ag, ProjectConfig as ah, ResolvedProjectConfig as ai, ResolveSnapshotPathHandler as aj, ResolveSnapshotPathHandlerContext as ak, TypecheckConfig as al, VitestEnvironment as am, BaseCoverageOptions as an, CoverageIstanbulOptions as ao, CoverageOptions as ap, CoverageProvider as aq, CoverageProviderModule as ar, CoverageReporter as as, CustomProviderOptions as at, TestRunResult as au, ReportedHookContext as av, Reporter as aw, TestRunEndReason as ax, ReportContext as b, CoverageV8Options as c, UserProjectConfigFn as d, UserProjectConfigExport as e, UserConfig as f, TestProjectInlineConfiguration as g, ResolvedConfig as h, VitestRunMode as i, VitestOptions as j, TestSequencer as l, OnTestsRerunHandler as m, JUnitOptions as o, TaskOptions as p, TestDiagnostic as s, TestModuleState as u, TestResult as v, TestResultFailed as w, TestResultPassed as x, TestResultSkipped as y, TestState as z };