### Link Locally Built Vitest to a Project with pnpm Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md Explains how to link a globally installed, locally built Vitest package into another project using pnpm. This enables the target project to utilize the development version of Vitest. ```bash pnpm link --global vitest ``` -------------------------------- ### Set Up Local Vitest Development Environment with pnpm Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md Provides a step-by-step guide to cloning, installing dependencies, building, and globally linking the Vitest project for local development and testing using pnpm. This allows developers to test their own modifications. ```bash git clone https://github.com/vitest-dev/vitest.git cd vitest pnpm install cd packages/vitest pnpm run build pnpm link --global # you can use your preferred package manager for this step ``` -------------------------------- ### Install Unreleased Vitest Commits via pkg.pr.new Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md Demonstrates how to install a specific unreleased commit of Vitest from the `pkg.pr.new` service using npm, targeting commits on the main branch or `cr-tracked` PRs. ```bash npm i https://pkg.pr.new/vitest@{commit} ``` -------------------------------- ### Configure Test Script in package.json Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md Add a test script to your package.json to enable running tests with npm run test, yarn test, or pnpm test commands. This configuration allows Vitest to execute all tests in your project. ```json { "scripts": { "test": "vitest" } } ``` -------------------------------- ### Install Vitest via Package Managers Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md Install Vitest as a development dependency using npm, yarn, pnpm, or bun. Vitest requires Vite >=v6.0.0 and Node >=v20.0.0. Choose the appropriate command based on your package manager. ```bash npm install -D vitest ``` ```bash yarn add -D vitest ``` ```bash pnpm add -D vitest ``` ```bash bun add -D vitest ``` -------------------------------- ### Write Test for Sum Function with Vitest Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md Create a test file using Vitest's test and expect APIs to verify that the sum function correctly adds 1 + 2 to equal 3. Test files must contain .test. or .spec. in their filename. ```javascript import { expect, test } from 'vitest' import { sum } from './sum.js' test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3) }) ``` -------------------------------- ### FUNCTION start Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/vitest.md Initializes reporters, the coverage provider, and runs tests. It accepts string filters and should not be called if `vitest.init()` has already been invoked. ```APIDOC ## FUNCTION start ### Description Initialize reporters, the coverage provider, and run tests. This method accepts string filters to match the test files - these are the same filters that [CLI supports](/guide/filtering#cli).\n\n::: warning\nThis method should not be called if [`vitest.init()`](#init) is also invoked. Use [`runTestSpecifications`](#runtestspecifications) or [`rerunTestSpecifications`](#reruntestspecifications) instead if you need to run tests after Vitest was initialised.\n:::\n\nThis method is called automatically by [`startVitest`](/guide/advanced/tests) if `config.mergeReports` and `config.standalone` are not set. ### Method FUNCTION ### Endpoint start ### Parameters #### Query Parameters - **filters** (string[]) - Optional - String filters to match the test files. #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **returnValue** (Promise) - The result of the test run. #### Response Example N/A ``` -------------------------------- ### Integrate Vitest into an existing Vite configuration Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md For projects already using Vite, Vitest configuration can be added directly to the `vite.config.ts` file. This approach requires adding a triple-slash directive to reference Vitest types, ensuring proper type checking and intellisense for the `test` property within `defineConfig`. ```TypeScript /// import { defineConfig } from 'vite' export default defineConfig({ test: { // ... }, }) ``` -------------------------------- ### Create Sum Function in JavaScript Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md Define a simple utility function that adds two numbers. This function will be tested in the corresponding test file to demonstrate basic Vitest functionality. ```javascript export function sum(a, b) { return a + b } ``` -------------------------------- ### Merge separate Vite and Vitest configurations Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md If maintaining separate configuration files for Vite and Vitest is preferred, use the `mergeConfig` utility from `vitest/config` or `vite`. This method allows combining settings from a `vite.config.mjs` and a `vitest.config.mjs` to ensure both configurations are applied without one overriding the other. ```TypeScript import { defineConfig, mergeConfig } from 'vitest/config' import viteConfig from './vite.config.mjs' export default mergeConfig(viteConfig, defineConfig({ test: { // ... }, })) ``` ```TypeScript import { defineConfig } from 'vite' import Vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [Vue()], }) ``` -------------------------------- ### Configure Vitest without an existing Vite setup Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md When Vitest is used without an existing Vite build tool setup, define its configuration within a dedicated `vitest.config.ts` file. This configuration uses the `defineConfig` utility and places all test-specific options under the `test` property. ```TypeScript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { // ... }, }) ``` -------------------------------- ### Start Vitest UI development server (bash) Source: https://github.com/vitest-dev/vitest/blob/main/packages/ui/README.md This command initiates the development server for the Vitest UI. It should be run in a terminal at the project root to make the UI accessible via a local URL. ```bash nr ui:dev ``` -------------------------------- ### Start Vitest UI development server with custom port (bash) Source: https://github.com/vitest-dev/vitest/blob/main/packages/ui/README.md This command starts the Vitest UI development server on a specified custom port (e.g., 3200) by setting the `VITE_PORT` environmental variable. This is useful for avoiding port conflicts or specific networking requirements. ```bash VITE_PORT=3200 nr ui:dev ``` -------------------------------- ### Define multiple test projects in Vitest configuration Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md Vitest supports defining multiple test projects within a single `vitest.config.ts` file, enabling different test configurations for various parts of your codebase. This feature allows specifying glob patterns for project files or defining distinct configurations with specific environments and setup files. ```TypeScript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { projects: [ // you can use a list of glob patterns to define your projects // Vitest expects a list of config files // or directories where there is a config file 'packages/*', 'tests/*/vitest.config.{e2e,unit}.ts', // you can even run the same tests, // but with different configs in the same "vitest" process { test: { name: 'happy-dom', root: './shared_tests', environment: 'happy-dom', setupFiles: ['./setup.happy-dom.ts'], } }, { test: { name: 'node', root: './shared_tests', environment: 'node', setupFiles: ['./setup.node.ts'], } } ] } }) ``` -------------------------------- ### start - Initialize and Run Tests Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/vitest.md Initializes reporters and coverage provider, then executes tests with optional string filters for test file matching. Should not be called alongside vitest.init(); use runTestSpecifications or rerunTestSpecifications instead if Vitest was already initialized. Called automatically by startVitest when config.mergeReports and config.standalone are not set. ```typescript function start(filters?: string[]): Promise ``` -------------------------------- ### Start Jaeger Service with Docker Compose Source: https://github.com/vitest-dev/vitest/blob/main/examples/opentelemetry/README.md Launches a Jaeger service container using Docker Compose to receive OTLP traces over HTTP and serve a Web UI for trace visualization at http://localhost:16686. ```shell docker compose up -d ``` -------------------------------- ### Initialize Vitest Instance for Manual Control with createVitest (TypeScript) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/advanced/tests.md This code shows how to use `createVitest` to create a Vitest instance without immediately running tests. It allows setting up event handlers for cancellations, closures, and test reruns. The snippet then explicitly starts tests, handles potential errors, and ensures the Vitest instance is properly closed. ```ts import { createVitest } from 'vitest/node' const vitest = await createVitest( 'test', {}, // override test config {}, // override Vite config {}, // custom Vitest options ) // called when `vitest.cancelCurrentRun()` is invoked vitest.onCancel(() => {}) // called during `vitest.close()` call vitest.onClose(() => {}) // called when Vitest reruns test files vitest.onTestsRerun((files) => {}) try { // this will set process.exitCode to 1 if tests failed, // and won't close the process automatically await vitest.start(['my-filter']) } catch (err) { // this can throw // "FilesNotFoundError" if no files were found // "GitNotFoundError" with `--changed` and repository is not initialized } finally { await vitest.close() } ``` -------------------------------- ### POST onInit Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/reporters.md Called when Vitest is initiated or started, but before tests are filtered. This method is invoked inside vitest.start(), vitest.init(), or vitest.mergeReports(). Use this to initialize reporter state and store a reference to the Vitest instance. ```APIDOC ## POST onInit ### Description This method is called when Vitest was initiated or started, but before the tests were filtered. It is invoked internally inside vitest.start(), vitest.init(), or vitest.mergeReports(). ### Method POST ### Signature ```ts function onInit(vitest: Vitest): Awaitable ``` ### Parameters #### Function Parameters - **vitest** (Vitest) - Required - The Vitest instance ### Usage Notes - Called inside vitest.start(), vitest.init(), or vitest.mergeReports() - When using programmatic API, ensure vitest.init() or vitest.start() is called before vitest.runTestSpecifications() - Built-in CLI automatically runs methods in correct order - You can also access vitest via the project property on test cases, suites, and test modules - Useful for storing a reference to the vitest instance for later use ### Request Example ```ts import type { Reporter, TestSpecification, Vitest } from 'vitest/node' class MyReporter implements Reporter { private vitest!: Vitest onInit(vitest: Vitest) { this.vitest = vitest } onTestRunStart(specifications: TestSpecification[]) { console.log( specifications.length, 'test files will run in', this.vitest.config.root, ) } } export default new MyReporter() ``` ### Response #### Success Response - Method returns Awaitable - No specific return value required ``` -------------------------------- ### Handle Test Run Start with Specifications Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/reporters.md Implement onTestRunStart to receive and process test specifications when a new test run begins. This method receives a readonly array of TestSpecification objects representing scheduled tests. It's called even with an empty array if no test files are found. ```typescript import type { Reporter, TestSpecification } from 'vitest/node' class MyReporter implements Reporter { onTestRunStart(specifications: TestSpecification[]) { console.log(specifications.length, 'test files will run') } } export default new MyReporter() ``` -------------------------------- ### Start snapshot run and configure options Source: https://github.com/vitest-dev/vitest/blob/main/packages/snapshot/README.md Configures snapshot options with updateSnapshot mode and snapshotEnvironment, then initiates the current test run. The startCurrentRun method prepares the client to accept snapshot assertions for the specified file and test name with the given configuration. ```javascript const options = { updateSnapshot: 'new', snapshotEnvironment: environment, } await client.startCurrentRun( getCurrentFilepath(), getCurrentTestName(), options ) ``` -------------------------------- ### Wait for Server Readiness with `vi.waitFor` in Vitest Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/vi.md This example demonstrates using Vitest's `vi.waitFor` to asynchronously wait for a server to become ready. It repeatedly checks the `server.isReady` status within the callback, throwing an error if the server is not yet started, until the condition is met or the specified timeout is reached. It uses default Vitest test utilities and a mock `createServer` function. ```ts import { expect, test, vi } from 'vitest' import { createServer } from './server.js' test('Server started successfully', async () => { const server = createServer() await vi.waitFor( () => { if (!server.isReady) { throw new Error('Server not started') } console.log('Server started') }, { timeout: 500, // default is 1000 interval: 20, // default is 50 } ) expect(server.isReady).toBe(true) }) ``` -------------------------------- ### Start Vitest Tests Programmatically (Node.js) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/advanced/index.md The `startVitest` function initiates Vitest test execution directly from a Node.js script. It returns a `Vitest` instance, automatically handles closing in non-watch mode, and allows filtering tests by file path or passing CLI arguments and Vite overrides. Test results can be retrieved via `vitest.state.getTestModules()` after execution. ```typescript function startVitest( mode: VitestRunMode, cliFilters: string[] = [], options: CliOptions = {}, viteOverrides?: ViteUserConfig, vitestOptions?: VitestOptions, ): Promise ``` ```javascript import { startVitest } from 'vitest/node' const vitest = await startVitest('test') await vitest.close() ``` ```typescript import type { TestModule } from 'vitest/node' const vitest = await startVitest('test') console.log(vitest.state.getTestModules()) // [TestModule] ``` -------------------------------- ### Run Vitest with UI Flag Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/ui.md Start Vitest with the --ui flag to launch the interactive UI. The UI will be available at http://localhost:51204/__vitest__/ and requires watch mode to be active. ```bash vitest --ui ``` -------------------------------- ### onHookStart - Monitor Hook Execution Start Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/reporters.md Called when test hooks (beforeAll, afterAll, beforeEach, afterEach) begin execution. The entity context will be either TestSuite/TestModule for beforeAll/afterAll or TestCase for beforeEach/afterEach. Note: This method is not called if the hook did not run during the test execution. ```typescript function onHookStart(context: ReportedHookContext): Awaitable ``` -------------------------------- ### onTestSuiteReady - Handle Test Suite Preparation Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/reporters.md Called before a test suite starts running its tests, and also when the suite is skipped. This method is not called if the file contains no suites; use onTestModuleStart as an alternative for that scenario. ```typescript function onTestSuiteReady(testSuite: TestSuite): Awaitable ``` -------------------------------- ### POST onTestRunStart Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/reporters.md Called when a new test run has started. Receives an array of test specifications scheduled to run. If no test files are found, this is invoked with an empty array followed immediately by onTestRunEnd. ```APIDOC ## POST onTestRunStart ### Description This method is called when a new test run has started. It receives an array of test specifications scheduled to run. If Vitest didn't find any test files to run, this event will be invoked with an empty array, and then onTestRunEnd will be called immediately after. ### Method POST ### Signature ```ts function onTestRunStart( specifications: TestSpecification[] ): Awaitable ``` ### Parameters #### Function Parameters - **specifications** (TestSpecification[]) - Required - Array of test specifications scheduled to run (readonly) ### Usage Notes - Array is readonly and available for information purposes only - Empty array indicates no test files were found to run - If empty array is provided, onTestRunEnd will be called immediately after - Replaces deprecated onPathsCollected and onSpecsCollected (as of Vitest 3) ### Request Example ```ts import type { Reporter, TestSpecification } from 'vitest/node' class MyReporter implements Reporter { onTestRunStart(specifications: TestSpecification[]) { console.log(specifications.length, 'test files will run') } } export default new MyReporter() ``` ### Response #### Success Response - Method returns Awaitable - No specific return value required ### Deprecation Notice This method was added in Vitest 3, replacing onPathsCollected and onSpecsCollected, both of which are now deprecated. ``` -------------------------------- ### Implement Reusable Test Setup and Teardown with `onTestFinished` in Vitest Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/index.md This example illustrates how to encapsulate setup and cleanup logic into a reusable function using `onTestFinished`. The `getTestDb` function creates a mocked database connection and registers a cleanup callback, ensuring that each test gets its own isolated, properly managed database instance. ```ts // this can be in a separate file function getTestDb() { const db = connectMockedDb() onTestFinished(() => db.close()) return db } test('performs a user query', async () => { const db = getTestDb() expect( await db.query('SELECT * from users').perform() ).toEqual([]) }) test('performs an organization query', async () => { const db = getTestDb() expect( await db.query('SELECT * from organizations').perform() ).toEqual([]) }) ``` -------------------------------- ### all() - Get All Matching Locators Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/locators.md Returns an array of new locators that match the selector. Internally calls elements() and wraps each element using page.elementLocator. ```APIDOC ## all() ### Description Returns an array of new locators that match the selector. This method wraps each matched element as a locator using `page.elementLocator`. ### Method Synchronous function ### Function Signature ```ts function all(): Locator[] ``` ### Return Value - Returns `Locator[]` - Array of locators matching the selector ### Implementation Details Internally, this method: 1. Calls `.elements()` to get all matching elements 2. Wraps every element using [`page.elementLocator`](/api/browser/context#page) ### Related Methods - See [`.elements()`](#elements) for getting raw DOM elements - Use [`.query()`](#query) to get a single element or null - Use [`.element()`](#element) to get a single element (throws if not found) ``` -------------------------------- ### Implement Vitest beforeAll/afterAll hooks for per-suite setup Source: https://context7.com/vitest-dev/vitest/llms.txt `beforeAll` and `afterAll` hooks execute setup and cleanup code *once* before and after all tests in a `describe` block. This is useful for expensive operations like starting a server or connecting to a database that can be shared across multiple tests in the same suite. These hooks are also asynchronous. ```typescript import { describe, it, expect, beforeAll, afterAll } from 'vitest' describe('Server tests', () => { let server: Server let baseUrl: string beforeAll(async () => { // Runs once before all tests in suite server = await startServer({ port: 0 }) baseUrl = `http://localhost:${server.port}` }) afterAll(async () => { // Runs once after all tests in suite await server.close() }) it('GET /health returns 200', async () => { const response = await fetch(`${baseUrl}/health`) expect(response.status).toBe(200) }) it('GET /api/users returns array', async () => { const response = await fetch(`${baseUrl}/api/users`) const data = await response.json() expect(Array.isArray(data)).toBe(true) }) }) ``` -------------------------------- ### GET diagnostic() Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/test-case.md Provides useful diagnostic information about the test's execution, such as duration, memory usage, and retry counts. Returns `undefined` if the test hasn't started yet. ```APIDOC ## GET /diagnostic ### Description Provides useful diagnostic information about the test's execution, such as duration, memory usage, and retry counts. Returns `undefined` if the test hasn't started yet. ### Method GET ### Endpoint /diagnostic ### Parameters This function does not accept any parameters. ### Request Body N/A ### Request Example N/A ### Response Returns a `TestDiagnostic` object or `undefined` (represented as `null` in JSON). #### TestDiagnostic - **slow** (boolean) - `true` if the test duration exceeds `slowTestThreshold`. - **heap** (number | undefined) - Memory used by the test in bytes, if `logHeapUsage` is enabled. - **duration** (number) - Execution time of the test in milliseconds. - **startTime** (number) - Timestamp in milliseconds when the test started. - **retryCount** (number) - Number of times the test was retried. - **repeatCount** (number) - Number of times the test was repeated. - **flaky** (boolean) - `true` if the test passed on a second retry. ### Response Example ```json { "slow": false, "heap": 12345678, "duration": 50, "startTime": 1678886400000, "retryCount": 0, "repeatCount": 1, "flaky": false } ``` ```json null ``` ``` -------------------------------- ### Function Call: startVitest Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/advanced/tests.md The `startVitest` function initiates the Vitest environment, validates installed packages, and immediately executes tests based on the provided configuration and filters. It's suitable for direct test execution in a Node.js context where a quick, self-contained test run is needed. ```APIDOC ## Function Call: startVitest ### Description Initiates the Vitest environment, validates installed packages, and immediately executes tests based on the provided configuration and filters. It's suitable for direct test execution in a Node.js context where a quick, self-contained test run is needed. ### Method Function Call ### Parameters #### Arguments - **command** (string) - Required - The command to run, typically 'test'. - **cliFilters** (array) - Optional - An array of CLI filters to apply to tests. - **testConfig** (object) - Optional - An object to override Vitest test configuration. - **viteConfig** (object) - Optional - An object to override Vite configuration. - **vitestOptions** (object) - Optional - An object for custom Vitest options. ### Request Example ```ts import { startVitest } from 'vitest/node' const vitest = await startVitest( 'test', [], // CLI filters {}, // override test config {}, // override Vite config {}, // custom Vitest options ) const testModules = vitest.state.getTestModules() for (const testModule of testModules) { console.log(testModule.moduleId, testModule.ok() ? 'passed' : 'failed') } ``` ### Response #### Success Response (Vitest Instance) - **vitest** (object) - An instance of the Vitest runner. - **vitest.state** (object) - Contains the current state of the Vitest instance. - **vitest.state.getTestModules()** (function) - Returns an array of `TestModule` objects representing the executed test files. #### TestModule Object - **moduleId** (string) - The identifier for the test module (e.g., file path). - **ok()** (boolean) - A method that returns `true` if all tests in the module passed, `false` otherwise. ### Response Example ```json // Example output from console.log in the request example "path/to/my-test-file.spec.ts passed" "path/to/another-test.test.ts failed" ``` *(Note: The actual return value is a Vitest instance, not JSON. The console output shows how the instance is typically consumed.)* ``` -------------------------------- ### Run Vitest Tests Immediately with startVitest (TypeScript) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/advanced/tests.md This snippet demonstrates how to use `startVitest` to initiate and immediately run Vitest tests from a Node.js script. It validates package installations and allows overriding test and Vite configurations. After execution, it iterates through test modules to report their pass/fail status. ```ts import { startVitest } from 'vitest/node' const vitest = await startVitest( 'test', [], // CLI filters {}, // override test config {}, // override Vite config {}, // custom Vitest options ) const testModules = vitest.state.getTestModules() for (const testModule of testModules) { console.log(testModule.moduleId, testModule.ok() ? 'passed' : 'failed') } ``` -------------------------------- ### elements() - Get All Matching Elements Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/locators.md Returns an array of all elements matching the locator's selector. Never throws an error and returns an empty array if no elements match. ```APIDOC ## elements() ### Description Returns an array of elements matching the locator's selector. This function never throws an error and returns an empty array if there are no matching elements. ### Method Synchronous function ### Function Signature ```ts function elements(): Element[] ``` ### Return Value - Returns `Element[]` - Array of matching DOM elements (empty array if no matches) ### Usage Examples These locators will always succeed: ```ts page.getByText('Hello World').elements() // ✅ [HTMLElement] page.getByText('World').elements() // ✅ [HTMLElement] page.getByText('Hello', { exact: true }).elements() // ✅ [HTMLElement] page.getByText('Hello').elements() // ✅ [HTMLElement, HTMLElement] page.getByText('Hello USA').elements() // ✅ [] ``` ### Related Methods - Use [`.query()`](#query) to get a single element or null - Use [`.element()`](#element) to get a single element (throws if not found) - Use [`.all()`](#all) to get an array of locators instead of elements ``` -------------------------------- ### Launch Vitest with Node Inspector for Debugging (CLI) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/debugging.md These command-line examples demonstrate how to launch Vitest with Node.js inspector support, enabling debugging without an IDE. The `--inspect-brk` flag pauses execution at the start, waiting for a debugger to connect (e.g., Chrome DevTools). The `--no-file-parallelism` flag is crucial as debugging requires tests to run in a single worker, preventing conflicts with the inspector. ```sh vitest --inspect-brk --no-file-parallelism ``` ```sh vitest --inspect-brk --browser --no-file-parallelism ``` -------------------------------- ### createCoverageProvider - Initialize Coverage Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/vitest.md Creates a coverage provider if coverage is enabled in the configuration. This is done automatically when running tests with start or init methods. Cleans previous reports if coverage.clean is not set to false. ```APIDOC ## createCoverageProvider ### Description Creates a coverage provider if coverage is enabled in the config. This is done automatically if you are running tests with start or init methods. This method will also clean all previous reports if coverage.clean is not set to false. ### Method Function ### Signature ```ts function createCoverageProvider(): Promise ``` ### Response - **Promise** - A promise that resolves to a CoverageProvider instance if coverage is enabled, or null otherwise. ### Example ```ts const provider = await vitest.createCoverageProvider() if (provider) { console.log('Coverage provider initialized') } ``` ### Version 4.0.0+ ### Warning This method will clean all previous reports if coverage.clean is not set to false. ``` -------------------------------- ### onTestCaseReady Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/reporters.md This hook is invoked before a test case starts execution or if it was skipped. It provides the `TestCase` object. Note that `beforeEach` and `afterEach` hooks are considered part of the test lifecycle. ```APIDOC ## onTestCaseReady ### Description This method is called before the test starts to run or it was skipped. Note that `beforeEach` and `afterEach` hooks are considered part of the test because they can influence the result. Note: it's possible to have `testCase.result()` with `passed` or `failed` state already when `onTestCaseReady` is called. This can happen if test was running too fast and both `onTestCaseReady` and `onTestCaseResult` were scheduled to run in the same microtask. ### Method Hook Function ### Function Signature `function onTestCaseReady(testCase: TestCase): Awaitable` ### Parameters #### Function Parameters - **testCase** (TestCase) - Required - The test case that is ready to run. ### Response #### Return Value - `Awaitable` - The hook function is asynchronous and doesn't return a specific value, indicating completion. ``` -------------------------------- ### onTestModuleStart Hook - Track Test Module Execution Start Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/reporters.md Called right after onTestModuleCollected unless Vitest runs in collection mode. Not invoked during collection-only runs where tests are not executed. ```TypeScript function onTestModuleStart(testModule: TestModule): Awaitable ``` -------------------------------- ### Implement Vitest beforeEach/afterEach hooks for per-test setup Source: https://context7.com/vitest-dev/vitest/llms.txt Use `beforeEach` and `afterEach` hooks to run setup and cleanup code before and after *each* test within a `describe` block. This ensures that tests start with a clean slate and resources are properly released, preventing test interference. These hooks are asynchronous and can await promises. ```typescript import { describe, it, expect, beforeEach, afterEach } from 'vitest' describe('Database tests', () => { let db: Database beforeEach(async () => { // Runs before each test db = await createTestDatabase() await db.seed() }) afterEach(async () => { // Runs after each test await db.cleanup() await db.close() }) it('inserts records', async () => { await db.insert({ name: 'Alice' }) const records = await db.findAll() expect(records).toHaveLength(1) }) it('updates records', async () => { const id = await db.insert({ name: 'Bob' }) await db.update(id, { name: 'Charlie' }) const record = await db.findById(id) expect(record.name).toBe('Charlie') }) }) ``` -------------------------------- ### sequence.setupFiles Configuration Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/cli-generated.md Controls the execution order of setup files during test initialization. Can be set to either 'list' for sequential execution or 'parallel' for concurrent execution. Default behavior is parallel execution. ```APIDOC ## sequence.setupFiles ### Description Changes the order in which setup files are executed. ### CLI Usage ``` --sequence.setupFiles ``` ### Configuration Refer to [sequence.setupFiles](/config/sequence#sequence-setupfiles) ### Parameters - **order** (string) - Required - Execution order for setup files - Accepted values: `"list"`, `"parallel"` - `"list"`: Run setup files sequentially in defined order - `"parallel"`: Run setup files concurrently (default) ### Default Value ``` "parallel" ``` ``` -------------------------------- ### GET /items Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/expect-typeof.md Provides access to `expectTypeOf.items`, allowing assertion on the item type of an array. ```APIDOC ## GET /items ### Description You can get array item type with `.items` to perform further assertions. Returns `ExpectTypeOf` where `T` is the array item type. ### Method GET (Utility Property) ### Endpoint /items ### Parameters N/A ### Request Body N/A ### Request Example ```typescript import { expectTypeOf } from 'vitest' expectTypeOf([1, 2, 3]).items.toEqualTypeOf() expectTypeOf([1, 2, 3]).items.not.toEqualTypeOf() ``` ### Response #### Success Response (200 - Implicit) - **type_assertion_chain** (ExpectTypeOf) - An `ExpectTypeOf` instance representing the array's item type for further assertions. #### Response Example ```typescript // Example of successful type assertion expectTypeOf().items.toBeString() ``` ``` -------------------------------- ### Initialize Vitest Browser Configuration (Bash) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/cli.md Initializes project configuration for specific Vitest features. Currently, it supports setting up the browser testing environment. ```bash vitest init browser ``` -------------------------------- ### GET /resolves Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/expect-typeof.md Provides access to `expectTypeOf.resolves`, allowing assertion on the resolved value of a `Promise`. If used on a non-promise type, it returns `never`. ```APIDOC ## GET /resolves ### Description This matcher extracts resolved value of a `Promise`, so you can perform other assertions on it. Returns `ExpectTypeOf`. If used on a non-promise type, it will return `never`. ### Method GET (Utility Property) ### Endpoint /resolves ### Parameters N/A ### Request Body N/A ### Request Example ```typescript import { expectTypeOf } from 'vitest' async function asyncFunc() { return 123 } expectTypeOf(asyncFunc).returns.resolves.toBeNumber() expectTypeOf(Promise.resolve('string')).resolves.toBeString() ``` ### Response #### Success Response (200 - Implicit) - **type_assertion_chain** (ExpectTypeOf) - An `ExpectTypeOf` instance representing the promise's resolved type for further assertions. #### Response Example ```typescript // Example of successful type assertion expectTypeOf(Promise.resolve(true)).resolves.toBeBoolean() ``` ``` -------------------------------- ### GET /instance Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/expect-typeof.md Provides access to `expectTypeOf.instance`, allowing assertions on an instance of the provided class. If used on a non-function type, it returns `never`. ```APIDOC ## GET /instance ### Description This property gives access to matchers that can be performed on an instance of the provided class. Returns `ExpectTypeOf`. If used on a non-function type, it will return `never`. ### Method GET (Utility Property) ### Endpoint /instance ### Parameters N/A ### Request Body N/A ### Request Example ```typescript import { expectTypeOf } from 'vitest' expectTypeOf(Date).instance.toHaveProperty('toISOString') ``` ### Response #### Success Response (200 - Implicit) - **type_assertion_chain** (ExpectTypeOf) - An `ExpectTypeOf` instance for the class's instance, allowing instance-specific assertions. #### Response Example ```typescript // Example of successful type assertion expectTypeOf(Array).instance.toHaveProperty('length') ``` ``` -------------------------------- ### Injecting serializable data from Vitest global setup into tests (v2 & v3) Source: https://github.com/vitest-dev/vitest/blob/main/docs/config/globalsetup.md This example demonstrates how to pass serializable data from a `globalSetup` file to individual tests using Vitest's `provide` mechanism. The `globalSetup` function provides a value (e.g., `wsPort`), which can then be injected and used within test files. This is useful for sharing configuration or resources that need to be set up globally, with syntax variations for Vitest v2 and v3. ```ts import { inject } from 'vitest' inject('wsPort') === 3000 ``` ```ts import type { TestProject } from 'vitest/node' export default function setup(project: TestProject) { project.provide('wsPort', 3000) } declare module 'vitest' { export interface ProvidedContext { wsPort: number } } ``` ```ts import type { GlobalSetupContext } from 'vitest/node' export default function setup({ provide }: GlobalSetupContext) { provide('wsPort', 3000) } declare module 'vitest' { export interface ProvidedContext { wsPort: number } } ``` -------------------------------- ### GET annotations() Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/test-case.md Retrieves an array of test annotations that were added during the test execution using the `task.annotate` API. ```APIDOC ## GET /annotations ### Description Retrieves an array of test annotations that were added during the test execution using the `task.annotate` API. ### Method GET ### Endpoint /annotations ### Parameters This function does not accept any parameters. ### Request Body N/A ### Request Example N/A ### Response Returns `ReadonlyArray`. The structure of `TestAnnotation` is not detailed in the provided text, but it represents custom metadata added during test execution. ### Response Example ```json [ { "type": "custom", "data": { "component": "UserWidget", "version": "1.2.0" } }, { "type": "info", "message": "Important note about test setup." } ] ``` ``` -------------------------------- ### Import Vitest's `vi` Helper Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/vi.md This snippet demonstrates the standard way to import the `vi` helper directly from the `vitest` package. The `vi` helper provides access to various utility functions and mocking capabilities within the Vitest testing framework. ```javascript import { vi } from 'vitest' ``` -------------------------------- ### GET /constructorParameters Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/expect-typeof.md Provides access to `expectTypeOf.constructorParameters`, allowing assertion on constructor arguments as an array of types. If used on a non-function type, it returns `never`. ```APIDOC ## GET /constructorParameters ### Description Extracts constructor parameters as an array of values and perform assertions on them with this method. Returns `ExpectTypeOf`. If used on a non-function type, it will return `never`. ### Method GET (Utility Property) ### Endpoint /constructorParameters ### Parameters N/A ### Request Body N/A ### Request Example ```typescript import { expectTypeOf } from 'vitest' expectTypeOf(Date).constructorParameters.toEqualTypeOf<[] | [string | number | Date]>() ``` ### Response #### Success Response (200 - Implicit) - **type_assertion_chain** (ExpectTypeOf) - An `ExpectTypeOf` instance representing the constructor's parameters as an array for further assertions. #### Response Example ```typescript // Example of successful type assertion expectTypeOf(Array).constructorParameters.toEqualTypeOf<[] | [number]>() ``` ``` -------------------------------- ### setupFiles Global Variable Configuration in Vitest Source: https://github.com/vitest-dev/vitest/blob/main/docs/config/setupfiles.md Demonstrates proper setup file patterns using global variables to avoid redundant initialization. This example shows how to conditionally initialize plugins and perform expensive computations only once, while ensuring cleanup hooks run between tests. Useful for distinguishing test execution across multiple workers using VITEST_POOL_ID. ```typescript import { config } from '@some-testing-lib' if (!globalThis.defined) { config.plugins = [myCoolPlugin] computeHeavyThing() globalThis.defined = true } // hooks are reset before each suite afterEach(() => { cleanup() }) globalThis.resetBeforeEachTest = true ``` -------------------------------- ### GET /parameters Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/expect-typeof.md Provides access to `expectTypeOf.parameters`, allowing assertion on function arguments as an array of types. If used on a non-function type, it returns `never`. ```APIDOC ## GET /parameters ### Description Extracts function arguments with `.parameters` to perform assertions on its value. Parameters are returned as an array. Returns `ExpectTypeOf`. If used on a non-function type, it will return `never`. ### Method GET (Utility Property) ### Endpoint /parameters ### Parameters N/A ### Request Body N/A ### Request Example ```typescript import { expectTypeOf } from 'vitest' type NoParam = () => void type HasParam = (s: string) => void expectTypeOf().parameters.toEqualTypeOf<[]>() expectTypeOf().parameters.toEqualTypeOf<[string]>() ``` ### Response #### Success Response (200 - Implicit) - **type_assertion_chain** (ExpectTypeOf) - An `ExpectTypeOf` instance representing the function's parameters as an array for further assertions. #### Response Example ```typescript // Example of successful type assertion expectTypeOf<() => void>().parameters.toEqualTypeOf<[]>() ``` ``` -------------------------------- ### Get Count of Waiting Timers with vi.getTimerCount Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/vi.md Returns the number of timers that are currently scheduled to run. This is useful for assertions and debugging timer-related test issues. ```typescript function getTimerCount(): number ``` -------------------------------- ### onHookStart Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/reporters.md This hook is invoked when `beforeAll`, `afterAll`, `beforeEach`, or `afterEach` hooks begin execution. It provides context about the running hook and the associated entity (TestSuite, TestModule, or TestCase). ```APIDOC ## onHookStart ### Description This method is called when any of these hooks have started running: `beforeAll`, `afterAll`, `beforeEach`, `afterEach`. If `beforeAll` or `afterAll` are started, the `entity` will be either `TestSuite` or `TestModule`. If `beforeEach` or `afterEach` are started, the `entity` will always be `TestCase`. Note: `onHookStart` method will not be called if the hook did not run during the test run. ### Method Hook Function ### Function Signature `function onHookStart(context: ReportedHookContext): Awaitable` ### Parameters #### Function Parameters - **context** (ReportedHookContext) - Required - Contextual information about the started hook. ### Response #### Return Value - `Awaitable` - The hook function is asynchronous and doesn't return a specific value, indicating completion. ``` -------------------------------- ### GET artifacts() Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/test-case.md Retrieves an array of test artifacts that were recorded during the test execution using the `recordArtifact` API. This feature is experimental. ```APIDOC ## GET /artifacts ### Description Retrieves an array of test artifacts that were recorded during the test execution using the `recordArtifact` API. This feature is experimental. ### Method GET ### Endpoint /artifacts ### Parameters This function does not accept any parameters. ### Request Body N/A ### Request Example N/A ### Response Returns `ReadonlyArray`. The structure of `TestArtifact` is not detailed in the provided text, but it represents recorded output or files from the test run. ### Response Example ```json [ { "name": "screenshot.png", "mimeType": "image/png", "path": "/tmp/test_artifacts/screenshot.png", "size": 150000 }, { "name": "log_output.txt", "mimeType": "text/plain", "content": "Test run log: Process started. Data processed. Process finished." } ] ``` ``` -------------------------------- ### Create Vitest Instance Without Running Tests (Node.js) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/advanced/index.md The `createVitest` function generates a `Vitest` instance without immediately starting tests or validating installed packages. This is useful for scenarios where you need to configure or inspect the Vitest environment before initiating test runs, providing a programmatic setup similar to `startVitest` but with deferred execution. ```typescript function createVitest( mode: VitestRunMode, options: CliOptions, viteOverrides: ViteUserConfig = {}, vitestOptions: VitestOptions = {}, ): Promise ``` ```javascript import { createVitest } from 'vitest/node' const vitest = await createVitest('test', { watch: false, }) ``` -------------------------------- ### import Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/test-project.md Imports a module using Vite's module runner, applying the project's configuration for transformation. The module is executed in a separate context and will not be the same instance as a regular static import. ```APIDOC ## Function Call import ### Description Import a file using Vite module runner. The file will be transformed by Vite with provided project's config and executed in a separate context. Note that `moduleId` will be relative to the `config.root`. ### Method Function Call ### Endpoint import ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body - **moduleId** (string) - Required - The module ID (relative to `config.root`) of the file to import. ### Request Example ```ts import * as staticExample from './example.js' const dynamicExample = await project.import('./example.js') dynamicExample !== staticExample // ✅ ``` ### Response #### Success Response (Module) - **module** (any) - The imported module's exports. #### Response Example (Not explicitly provided, returns the module's exports) ``` -------------------------------- ### Configure OpenTelemetry SDK with Node Auto Instrumentations Source: https://github.com/vitest-dev/vitest/blob/main/docs/config/experimental.md JavaScript module that initializes and exports a started NodeSDK instance with automatic instrumentations and OTLP trace exporting. This file is imported by Vitest to enable distributed tracing and performance monitoring. ```javascript import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node' import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto' import { NodeSDK } from '@opentelemetry/sdk-node' const sdk = new NodeSDK({ serviceName: 'vitest', traceExporter: new OTLPTraceExporter(), instrumentations: [getNodeAutoInstrumentations()], }) sdk.start() export default sdk ```