### Build and set up wasm-bindgen hello_world example Source: https://github.com/vitest-dev/vitest/blob/main/test/unit/src/wasm/wasm-bindgen-no-cyclic/README.md Installs dependencies, builds the project, and details the manual steps required to copy the package output and add module configuration to package.json. ```sh npm i npm run build # then # 1. copy `examples/hello_world/pkg` to this directory # 2. add { "type": "module" } to `package.json` # (this will be automatically included after https://github.com/rustwasm/wasm-pack/pull/1061) ``` -------------------------------- ### Run example tests with CI=true pnpm test:examples Source: https://github.com/vitest-dev/vitest/blob/main/AGENTS.md Runs the example tests in CI mode. Use to verify examples. ```bash CI=true pnpm test:examples ``` -------------------------------- ### Configure global setup with setupFiles Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/learn/setup-teardown.md Point `setupFiles` in `vitest.config.js` to a setup file like `test/setup.js` that runs before every test file. Use this for global setup such as polyfills and extending matchers with `expect.extend` before test collection begins. ```javascript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { setupFiles: ['./test/setup.js'], }, }) ``` ```javascript // This runs before every test file import { expect } from 'vitest' import { customMatchers } from './custom-matchers.js' expect.extend(customMatchers) ``` -------------------------------- ### Define global setup and teardown using named exports Source: https://github.com/vitest-dev/vitest/blob/main/docs/config/globalsetup.md Export named `setup` and `teardown` functions in a global setup file. The `setup` function receives the `project` instance and runs before test workers are created. ```js export function setup(project) { console.log('setup') } export function teardown() { console.log('teardown') } ``` -------------------------------- ### Configure Vitest to use a custom OpenTelemetry SDK Source: https://github.com/vitest-dev/vitest/blob/main/docs/config/experimental.md Example otel.js file that starts a NodeSDK instance and exports it as default. Use this as the sdkPath in Vitest configuration to enable OpenTelemetry. ```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 ``` ```javascript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { experimental: { openTelemetry: { enabled: true, sdkPath: './otel.js', }, }, }, }) ``` -------------------------------- ### Generate HTML report and start UI dev server Source: https://github.com/vitest-dev/vitest/blob/main/packages/ui/CONTRIBUTING.md Generates an HTML report using the test:ui script and then starts the UI dev server pointing to the generated report directory. Use this as a complete example for HTML report development. ```bash pnpm -C packages/ui test:ui --reporter=html --run HTML_REPORT_DIR="$PWD/packages/ui/.vitest" pnpm -C packages/ui dev:client ``` -------------------------------- ### Installing @vitest/browser-preview Source: https://github.com/vitest-dev/vitest/blob/main/packages/browser-preview/README.md Install the @vitest/browser-preview package as a development dependency using npm, yarn, or pnpm. ```sh npm install -D @vitest/browser-preview # or yarn add -D @vitest/browser-preview # or pnpm add -D @vitest/browser-preview ``` -------------------------------- ### Install dependencies with pnpm Source: https://github.com/vitest-dev/vitest/blob/main/CONTRIBUTING.md Run this command in the root folder of the Vitest repository to install all dependencies. ```shell pnpm install ``` -------------------------------- ### Install @vitest/ui package Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/ui.md Install Vitest UI as a development dependency. ```bash npm i -D @vitest/ui ``` -------------------------------- ### Providing context from a global setup file Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/test-project.md Use provide within a global setup function when unable to use the Node.js public API directly. ```js export default function setup({ provide }) { provide('wsPort', 3000) } ``` -------------------------------- ### Start Vitest with Live UI Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/ui.md Start Vitest in watch mode with the interactive UI enabled. ```bash vitest --ui ``` -------------------------------- ### Run setup and teardown with beforeEach return callback Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/hooks.md Alternative to `aroundEach` when only simple pre-test setup and post-test cleanup are required without an enclosing context. ```typescript beforeEach(async () => { await database.connect() return async () => { await database.disconnect() } }) ``` -------------------------------- ### Install @vitest/web-worker Source: https://github.com/vitest-dev/vitest/blob/main/packages/web-worker/README.md Install the package as a development dependency using npm, pnpm, or yarn. ```bash # with npm npm install -D @vitest/web-worker # with pnpm pnpm install -D @vitest/web-worker # with yarn yarn add --dev @vitest/web-worker ``` -------------------------------- ### Example DOM structure for query and element Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/locators.md HTML structure used in the query and element examples. ```html
Hello World
Hello
``` -------------------------------- ### Install OpenTelemetry browser tracing dependencies Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/open-telemetry.md Installs the web trace SDK and OTLP proto exporter required for capturing traces in browser mode. ```shell npm i @opentelemetry/sdk-trace-web @opentelemetry/exporter-trace-otlp-proto ``` -------------------------------- ### Install @chromatic-com/vitest plugin Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/visual-regression-testing.md Install the Chromatic Vitest plugin using your package manager of choice as a development dependency. ```bash npm install -D @chromatic-com/vitest ``` ```bash yarn add -D @chromatic-com/vitest ``` ```bash pnpm add -D @chromatic-com/vitest ``` -------------------------------- ### Install Vitest using bun Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md Installs Vitest as a development dependency using bun. Vitest requires Vite >=v6.4.0 and Node >=v22.12.0. ```bash bun add -D vitest ``` -------------------------------- ### Manually install Vitest with WebdriverIO provider Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs Vitest and the WebdriverIO provider. WebdriverIO runs tests locally using the WebDriver protocol. ```bash npm install -D vitest @vitest/browser-webdriverio ``` ```bash yarn add -D vitest vite @vitest/browser-webdriverio ``` ```bash pnpm add -D vitest @vitest/browser-webdriverio ``` ```bash bun add -D vitest @vitest/browser-webdriverio ``` -------------------------------- ### vi.resetModules usage example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/vi.md Example showing that vi.resetModules clears the module cache so dynamic imports get fresh state, while top-level imports are not reevaluated. ```ts import { vi } from 'vitest' import { data } from './data.js' // Will not get reevaluated beforeEach test beforeEach(() => { vi.resetModules() }) test('change state', async () => { const mod = await import('./some/path.js') // Will get reevaluated mod.changeLocalState('new value') expect(mod.getLocalState()).toBe('new value') }) test('module has old state', async () => { const mod = await import('./some/path.js') // Will get reevaluated expect(mod.getLocalState()).toBe('old value') }) ``` -------------------------------- ### Configure and test different instance setups with provide and setupFiles Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/multiple-setups.md Defines multiple instance setups using custom names, setupFiles, and provide values, and consumes the injected values within a test file. ```ts import { defineConfig } from 'vitest/config' import { playwright } from '@vitest/browser-playwright' export default defineConfig({ test: { browser: { enabled: true, provider: playwright(), headless: true, instances: [ { precedence: undefined, browser: 'chromium', name: 'chromium-1', setupFiles: ['./ratio-setup.ts'], provide: { ratio: 1 } } as any ? { browser: 'chromium', name: 'chromium-1', setupFiles: ['./ratio-setup.ts'], provide: { ratio: 1, }, } : null, { browser: 'chromium', name: 'chromium-2', provide: { ratio: 2, }, }, ], }, }, }) ``` ```ts import { expect, inject, test } from 'vitest' import { globalSetupModifier } from './example.js' test('ratio works', () => { expect(inject('ratio') * globalSetupModifier).toBe(14) }) ``` -------------------------------- ### createVitest(options, viteOverrides?, vitestOptions?) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/advanced/index.md Creates a Vitest instance without automatically starting tests or validating installed packages. It returns the same Vitest instance as startVitest. ```APIDOC ## createVitest ### Description Creates a Vitest instance using the provided options. Returns the same `Vitest` instance as `startVitest`, but does not start tests or validate installed packages. ### Function Signature ```ts function createVitest( options: CliOptions, viteOverrides: ViteUserConfig = {}, vitestOptions: VitestOptions = {}, ): Promise ``` ### Parameters - **options** (`CliOptions`) - Required - Vitest CLI options. - **viteOverrides** (`ViteUserConfig`) - Optional - Overrides for Vite configuration. Defaults to `{}`. - **vitestOptions** (`VitestOptions`) - Optional - Additional Vitest options. Defaults to `{}`. ### Returns - `Promise` - A promise that resolves to a `Vitest` instance. ### Example ```js import { createVitest } from 'vitest/node' const vitest = await createVitest('test', { watch: false, }) ``` ``` -------------------------------- ### Run setup and teardown once using beforeAll cleanup function Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/hooks.md Demonstrates the preferred alternative to aroundAll when only simple setup and teardown are needed rather than an active wrapper context. ```typescript beforeAll(async () => { await server.start() return async () => { await server.stop() } }) ``` -------------------------------- ### Initialize browser setup with vitest init Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/cli.md `vitest init ` sets up project configuration. Currently only the `browser` value is supported. ```bash vitest init browser ``` -------------------------------- ### Define createVitest Type Signature Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/advanced/index.md Type definition for createVitest, returning a Promise that resolves to a Vitest instance without starting tests or validating installed packages. ```typescript function createVitest( options: CliOptions, viteOverrides: ViteUserConfig = {}, vitestOptions: VitestOptions = {}, ): Promise ``` -------------------------------- ### startVitest(cliFilters, testConfig, viteConfig, vitestOptions) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/advanced/tests.md Initiates Vitest, validates that required packages are installed, and runs tests immediately. It returns the active Vitest instance. ```APIDOC ## startVitest ### Description Initiates Vitest, validates that required packages are installed, and immediately executes the test suite. ### Signature `startVitest(cliFilters?, testConfig?, viteConfig?, vitestOptions?): Promise` ### Parameters - **cliFilters** (`string[]`) - Optional - Array of CLI filter patterns to filter tests to execute. - **testConfig** (`Record`) - Optional - Configuration object overriding Vitest test options. - **viteConfig** (`Record`) - Optional - Configuration object overriding Vite options. - **vitestOptions** (`Record`) - Optional - Custom Vitest CLI/node options. ### Usage Example ```ts import { startVitest } from 'vitest/node' const vitest = await startVitest( [], // 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') } ``` ``` -------------------------------- ### toHaveBeenNthCalledWith checks specific call arguments Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/expect.md Use with a spy to assert the arguments of a specific call, where the count starts at 1. The example verifies the first call to market.buy used 'apples', 10. ```ts import { expect, test, vi } from 'vitest' const market = { buy(subject: string, amount: number) { // ... }, } test('first call of spy function called with right params', () => { const buySpy = vi.spyOn(market, 'buy') market.buy('apples', 10) market.buy('apples', 20) expect(buySpy).toHaveBeenNthCalledWith(1, 'apples', 10) }) ``` -------------------------------- ### Perform one-time setup and teardown with beforeAll and afterAll Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/learn/setup-teardown.md Use beforeAll and afterAll to execute expensive operations once for an entire test file. Shared resources like database connections are created once, accessed across all file tests, and closed upon completion. ```javascript import { afterAll, beforeAll, expect, test } from 'vitest' let db beforeAll(async () => { db = await connectToDatabase() }) afterAll(async () => { await db.close() }) test('can query users', async () => { const users = await db.query('SELECT * FROM users') expect(users.length).toBeGreaterThan(0) }) test('can query products', async () => { const products = await db.query('SELECT * FROM products') expect(products.length).toBeGreaterThan(0) }) ``` -------------------------------- ### Run Playwright Server in Docker and connect via connectOptions Source: https://github.com/vitest-dev/vitest/blob/main/docs/config/browser/playwright.md Defines a Docker Compose setup to run a remote Playwright server, starts the container, and configures Vitest to connect via WebSocket. Uses `exposeNetwork: ''` to allow containerized browsers to access the host dev server. ```yaml services: playwright: image: mcr.microsoft.com/playwright:v1.61.0-noble command: /bin/sh -c "npx -y playwright@1.61.0 run-server --port 6677 --host 0.0.0.0" init: true ipc: host user: pwuser ports: - '6677:6677' ``` ```sh docker compose up -d ``` ```ts import { playwright } from '@vitest/browser-playwright' import { defineConfig } from 'vitest/config' export default defineConfig({ test: { browser: { provider: playwright({ connectOptions: { wsEndpoint: 'ws://127.0.0.1:6677/', exposeNetwork: '', }, }), instances: [ { browser: 'chromium' }, { browser: 'firefox' }, { browser: 'webkit' }, ], }, }, }) ``` -------------------------------- ### Start Vitest UI with token authentication Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/migration/index.md Run vitest --ui to start the UI. The printed URL includes a token; open it to authenticate, after which the direct /__vitest__/ URL works. ```bash vitest --ui # UI started at http://localhost:51204/__vitest__/?token=... ``` -------------------------------- ### userEvent.setup Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/interactivity.md Creates a new user event instance. This is useful if you need to keep the state of keyboard to press and release buttons correctly. ```APIDOC ## userEvent.setup ### Description Creates a new user event instance. This is useful if you need to keep the state of keyboard to press and release buttons correctly. ### Method `setup()` ### Parameters None. ### Returns - **UserEvent** - A new user event instance. ### Example ```ts import { userEvent } from 'vitest/browser' const user = userEvent.setup() await user.click(document.querySelector('.button')) ``` ``` -------------------------------- ### Execute setup logic before each test with beforeEach Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/hooks.md Registers an asynchronous setup function that runs prior to every test in the suite. Vitest waits for returned promises to resolve before test execution. ```ts import { beforeEach } from 'vitest' beforeEach(async () => { // Clear mocks and add some testing data before each test run await stopMocking() await addUser({ name: 'John' }) }) ``` -------------------------------- ### Example DOM structure for element Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/locators.md HTML structure used in the element examples. ```html
Hello World
Hello Germany
Hello
``` -------------------------------- ### Preview HTML report locally with vite preview Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/ui.md Start a local preview server serving the default .vitest output directory. ```sh npx vite preview --outDir .vitest ``` -------------------------------- ### vi.advanceTimersToNextFrame Example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/vi.md Example showing vi.advanceTimersToNextFrame triggering a requestAnimationFrame callback and asserting it ran. ```ts let frameRendered = false requestAnimationFrame(() => { frameRendered = true }) vi.advanceTimersToNextFrame() expect(frameRendered).toBe(true) ``` -------------------------------- ### toBeDisabled example HTML Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/assertions.md HTML markup for a disabled button used in the toBeDisabled example. ```html ``` -------------------------------- ### Manually install Vitest with preview provider Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs Vitest and the preview provider for local test preview. The preview provider simulates events and is not recommended for CI; use Playwright or WebdriverIO for CI. ```bash npm install -D vitest @vitest/browser-preview ``` ```bash yarn add -D vitest vite @vitest/browser-preview ``` ```bash pnpm add -D vitest @vitest/browser-preview ``` ```bash bun add -D vitest @vitest/browser-preview ``` -------------------------------- ### Configure browser.instances with inherited root config options Source: https://github.com/vitest-dev/vitest/blob/main/docs/config/browser/instances.md Demonstrates how browser instance configurations inherit options from the root config, such as setup files and testerHtmlPath. ```ts export default defineConfig({ test: { setupFile: ['./root-setup-file.js'], browser: { enabled: true, testerHtmlPath: './custom-path.html', instances: [ { // will have both setup files: "root" and "browser" setupFile: ['./browser-setup-file.js'], // implicitly has "testerHtmlPath" from the root config // [!code warning] // testerHtmlPath: './custom-path.html', // [!code warning] }, ], }, }, }) ``` -------------------------------- ### screenshot method TypeScript signatures Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/locators.md TypeScript overloads for the screenshot method. Use save: false to get a base64 string, base64: true to get both path and base64, or default to get only the file path. ```typescript function screenshot(options: LocatorScreenshotOptions & { save: false }): Promise function screenshot(options: LocatorScreenshotOptions & { base64: true }): Promise<{ path: string base64: string }> function screenshot(options?: LocatorScreenshotOptions & { base64?: false }): Promise ``` -------------------------------- ### Initialize Browser Mode with vitest init browser Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Automatically installs required dependencies and creates browser configuration. Run this command in your project root. ```bash npx vitest init browser ``` ```bash yarn exec vitest init browser ``` ```bash pnpx vitest init browser ``` ```bash bunx vitest init browser ``` -------------------------------- ### vi.runOnlyPendingTimers Example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/vi.md Example showing vi.runOnlyPendingTimers executing only the pending interval timer once, logging 1. ```ts let i = 0 setInterval(() => console.log(++i), 50) vi.runOnlyPendingTimers() // log: 1 ``` -------------------------------- ### vi.runAllTimersAsync Example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/vi.md Example showing await vi.runAllTimersAsync executing an asynchronous setTimeout that logs 'result'. ```ts setTimeout(async () => { console.log(await Promise.resolve('result')) }, 100) await vi.runAllTimersAsync() // log: result ``` -------------------------------- ### Define a sample class with fields and prototype methods Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/mocking/classes.md Demonstrates a class with both instance fields (greet) and prototype methods (speak, isHungry, and feed) to illustrate differences in mock behavior. ```ts class Dog { name: string constructor(name: string) { this.name = name } static getType(): string { return 'animal' } greet = (): string => { return `Hi! My name is ${this.name}!` } speak(): string { return 'bark!' } isHungry() {} feed() {} } ``` -------------------------------- ### Start Vitest UI/API server for test/unit Source: https://github.com/vitest-dev/vitest/blob/main/packages/ui/CONTRIBUTING.md Runs the test/unit suite with UI enabled to serve as the backend for the UI dev server. Use from the repository root. ```bash pnpm test --ui --open=false ``` -------------------------------- ### start Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/vitest.md Initializes reporters, the coverage provider, and runs tests. Accepts string filters to match test files, similar to CLI filters. Should not be called if standalone() is also invoked; use runTestSpecifications or rerunTestSpecifications instead for running tests after initialization. ```APIDOC ## 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. ::: warning This method should not be called if `vitest.standalone()` is also invoked. Use `runTestSpecifications` or `rerunTestSpecifications` instead if you need to run tests after Vitest was initialised. ::: This method is called automatically by `startVitest` if `config.mergeReports` and `config.standalone` are not set. ### Method `start` ### Parameters - **filters** (string[]) - Optional - String filters to match test files. ### Returns `Promise` ### Example ```ts const result = await vitest.start(['**/*.test.ts']); ``` ``` -------------------------------- ### toHaveFormValues usage example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/assertions.md TypeScript example asserting that a form has specific values for username and rememberMe fields. ```typescript await expect.element(getByTestId('login-form')).toHaveFormValues({ username: 'jane.doe', rememberMe: true, }) ``` -------------------------------- ### Configure per-file setup and global hooks in setup files Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/lifecycle.md Runs in the worker process before each test file executes. Use this file to initialize global state or register hooks that apply to all tests. ```ts import { afterEach } from 'vitest' // Runs before each test file console.log('Setup file executing') // Register hooks that apply to all tests afterEach(() => { cleanup() }) ``` -------------------------------- ### toContainHTML HTML Example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/assertions.md HTML structure used in the toContainHTML example, showing a parent and child element. ```html ``` -------------------------------- ### Initiate and run tests with startVitest Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/advanced/tests.md Uses `startVitest` to initiate Vitest, validate dependencies, run tests immediately, and inspect test module results. ```ts import { startVitest } from 'vitest/node' const vitest = await startVitest( [], // 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') } ``` -------------------------------- ### toContainElement HTML Example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/assertions.md HTML structure used in the toContainElement example, showing an ancestor and descendant element. ```html ``` -------------------------------- ### Set up Chromatic GitHub Action workflow in .github/workflows/chromatic.yml Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/visual-regression-testing.md Automate running Vitest and uploading snapshots to Chromatic within GitHub Actions using chromaui/action. ```yaml name: Chromatic on: push jobs: tests: name: Run Vitest & Chromatic runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v7 - uses: actions/setup-node@v7 with: node-version: 24 # ⚠️ See your package manager's documentation for the correct command to install dependencies in a CI environment. - name: Install dependencies run: npm ci - run: npx playwright install chromium --only-shell - name: Run Vitest tests run: npm run test - name: Run Chromatic uses: chromaui/action@latest with: # ⚠️ Enable Vitest vitest: true # ⚠️ Make sure to configure a `CHROMATIC_PROJECT_TOKEN` repository secret projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }} # ⚠️ Optionally configure the archive location with env vars to match your outputDirectory https://www.chromatic.com/docs/vitest/configure/#test-run-options env: CHROMATIC_ARCHIVE_LOCATION: .vitest/chromatic ``` -------------------------------- ### toBeEmptyDOMElement example HTML Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/assertions.md HTML markup with empty, whitespace, and comment elements used in the toBeEmptyDOMElement example. ```html ``` -------------------------------- ### startVitest(cliFilters, options, viteOverrides, vitestOptions) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/advanced/index.md Programmatically starts running Vitest tests using its Node.js API. Returns a Vitest instance if tests can be started. ```APIDOC ## startVitest ### Description Starts running Vitest tests using its Node API. If watch mode is not enabled, Vitest calls the `close` method automatically. If watch mode is enabled and the terminal supports TTY, it registers console shortcuts. ### Import ```ts import { startVitest } from 'vitest/node' ``` ### Signature ```ts function startVitest( cliFilters: string[] = [], options: CliOptions = {}, viteOverrides?: ViteUserConfig, vitestOptions?: VitestOptions, ): Promise ``` ### Parameters - **cliFilters** (`string[]`) - Optional (default: `[]`) - List of filters. Vitest will run only tests that contain at least one of the passed-down strings in their file path. - **options** (`CliOptions`) - Optional (default: `{}`) - CLI arguments overriding test config options. - **viteOverrides** (`ViteUserConfig`) - Optional - Complete Vite configuration taking precedence over other user-defined options. - **vitestOptions** (`VitestOptions`) - Optional - Vitest configuration options. ### Return Value - **Promise** - Returns a `Promise` resolving to a `Vitest` instance if tests can be started. ### Usage Example ```js import { startVitest } from 'vitest/node' const vitest = await startVitest() console.log(vitest.state.getTestModules()) await vitest.close() ``` ``` -------------------------------- ### Static meta example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/test-case.md Shows how to define static meta when creating a test, which is available even if the test has not finished running. ```ts test('the validation works correctly', { meta: { decorated: true } }) ``` -------------------------------- ### vi.advanceTimersByTime Example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/vi.md Example showing vi.advanceTimersByTime advancing an interval timer by 150ms, logging 1, 2, and 3. ```ts let i = 0 setInterval(() => console.log(++i), 50) vi.advanceTimersByTime(150) // log: 1 // log: 2 // log: 3 ``` -------------------------------- ### toHaveFocus usage example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/assertions.md TypeScript example showing how to focus and blur an input and assert focus state with toHaveFocus. ```typescript const input = page.getByTestId('element-to-focus') input.element().focus() await expect.element(input).toHaveFocus() input.element().blur() await expect.element(input).not.toHaveFocus() ``` -------------------------------- ### Example module for vi.doMock Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/vi.md A simple increment function used to demonstrate vi.doMock behavior. ```ts export function increment(number) { return number + 1 } ``` -------------------------------- ### vi.importActual usage example Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/vi.md Example of using vi.importActual to import the original module and then override a specific export with a mock. ```ts vi.mock('./example.js', async () => { const originalModule = await vi.importActual('./example.js') return { ...originalModule, get: vi.fn() } }) ``` -------------------------------- ### Installing @vitest/browser-playwright Source: https://github.com/vitest-dev/vitest/blob/main/packages/browser-playwright/README.md Install the Playwright browser provider package as a development dependency using npm, yarn, or pnpm. ```sh npm install -D @vitest/browser-playwright # or yarn add -D @vitest/browser-playwright # or pnpm add -D @vitest/browser-playwright ```