### 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 ``` -------------------------------- ### Render and test a Solid component with @testing-library/solid Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md For unsupported frameworks, use testing-library packages. This example renders a Solid app with routes at a given location and asserts the rendered param text using page.elementLocator. ```tsx // based on @testing-library/solid API // https://testing-library.com/docs/solid-testing-library/api import { render } from '@testing-library/solid' it('uses params', async () => { const App = () => ( <> (

Id: {useParams()?.id}

)} />

Start

} /> ) const { baseElement } = render(() => , { location: 'ids/1234' }) const screen = page.elementLocator(baseElement) await expect.screen(screen.getByText('Id: 1234')).toBeInTheDocument() }) ``` -------------------------------- ### 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 ``` -------------------------------- ### 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') } ``` -------------------------------- ### Render and test a Marko component with @marko/testing-library Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md For unsupported frameworks, use testing-library packages. This example renders a Marko Greeting component, asserts the text via page.elementLocator, and uses an inline snapshot for the rendered output. ```ts // based on @testing-library/marko API // https://testing-library.com/docs/marko-testing-library/api import { render, screen } from '@marko/testing-library' import Greeting from './greeting.marko' test('renders a message', async () => { const { baseElement } = await render(Greeting, { name: 'Marko' }) const screen = page.elementLocator(baseElement) await expect.element(screen.getByText(/Marko/)).toBeInTheDocument() expect(container.firstChild).toMatchInlineSnapshot(`

Hello, Marko!

`) }) ``` -------------------------------- ### 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) ``` -------------------------------- ### 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() } }) ``` -------------------------------- ### 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 ``` -------------------------------- ### provide values in global setup Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/advanced/test-project.md Shows how to use the provide method within a global setup file. ```js export default function setup({ provide }) { provide('wsPort', 3000) } ``` -------------------------------- ### 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) }) ``` -------------------------------- ### 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 ``` -------------------------------- ### 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() } }) ``` -------------------------------- ### 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=... ``` -------------------------------- ### 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 ``` -------------------------------- ### 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' }) }) ``` -------------------------------- ### 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 ``` -------------------------------- ### 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() ``` ``` -------------------------------- ### 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() }) ``` -------------------------------- ### 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
``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### Mock GraphQL queries with MSW in setup file Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/mocking/requests.md Sets up MSW `graphql` query handlers within a Vitest setup file to intercept GraphQL network traffic. Vitest lifecycle hooks manage server startup, teardown, and handler reset across tests. ```javascript import { afterAll, afterEach, beforeAll } from 'vitest' import { setupServer } from 'msw/node' import { graphql, HttpResponse } from 'msw' const posts = [ { userId: 1, id: 1, title: 'first post title', body: 'first post body', }, // ... ] const graphqlHandlers = [ graphql.query('ListPosts', () => { return HttpResponse.json({ data: { posts }, }) }), ] const server = setupServer(...graphqlHandlers) // Start server before all tests beforeAll(() => server.listen({ onUnhandledRequest: 'error' })) // Close server after all tests afterAll(() => server.close()) // Reset handlers after each test for test isolation afterEach(() => server.resetHandlers()) ``` -------------------------------- ### toBeInViewport Usage Examples Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/assertions.md Examples showing how to use toBeInViewport with different ratio values to assert element visibility in the viewport. ```typescript // A specific element is in viewport. await expect.element(page.getByText('Welcome')).toBeInViewport() // 50% of a specific element should be in viewport await expect.element(page.getByText('To')).toBeInViewport({ ratio: 0.5 }) // Full of a specific element should be in viewport await expect.element(page.getByText('Vitest')).toBeInViewport({ ratio: 1 }) ``` -------------------------------- ### Install happy-dom for DOM mocking Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/features.md Install happy-dom as a development dependency to mock DOM and browser APIs in Vitest. ```bash $ npm i -D happy-dom ``` -------------------------------- ### Start UI dev server for HTML report Source: https://github.com/vitest-dev/vitest/blob/main/packages/ui/CONTRIBUTING.md Starts the UI dev server for developing static HTML report UI with Vite HMR. Set HTML_REPORT_DIR to the path of the HTML report directory. ```bash HTML_REPORT_DIR= pnpm -C packages/ui dev:client ``` -------------------------------- ### Start UI dev server with custom VITE_PORT Source: https://github.com/vitest-dev/vitest/blob/main/packages/ui/CONTRIBUTING.md Starts the UI dev server when using a backend port other than the default 51204. Pass the same port as the backend. ```bash VITE_PORT=12345 pnpm -C packages/ui dev:client ``` -------------------------------- ### Install OpenTelemetry dependencies Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/open-telemetry.md Installs the required OpenTelemetry packages including Node SDK, automatic instrumentations, and OTLP proto trace exporter. ```shell npm i @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @opentelemetry/exporter-trace-otlp-proto ``` -------------------------------- ### Install jsdom for DOM mocking Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/features.md Install jsdom as a development dependency to mock DOM and browser APIs in Vitest. ```bash $ npm i -D jsdom ``` -------------------------------- ### Install Vitest using deno Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/index.md Installs Vitest as a development dependency using deno. Vitest requires Vite >=v6.4.0 and Node >=v22.12.0. ```bash deno add -D vitest ``` -------------------------------- ### 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 ``` -------------------------------- ### Identify shared state issues Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/learn/debugging-tests.md This example demonstrates how modifying shared variables between tests can cause unexpected failures. ```js // This is a problem: `users` is shared between tests const users = [] test('adds a user', () => { users.push('Alice') expect(users).toEqual(['Alice']) }) test('starts empty', () => { // This fails because 'Alice' is still in the array! expect(users).toEqual([]) }) ``` -------------------------------- ### 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() ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### Initialize browser mode with vitest init browser (bun) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs required dependencies and creates browser configuration automatically. Run with bun. ```bash bunx vitest init browser ``` -------------------------------- ### Start UI dev server in browser preview mode Source: https://github.com/vitest-dev/vitest/blob/main/packages/ui/CONTRIBUTING.md Starts the UI dev server with BROWSER_DEV=true to develop Browser Mode UI features. It fetches browser runner state from the browser runner server on port 23315 by default. ```bash BROWSER_DEV=true pnpm -C packages/ui dev:client ``` -------------------------------- ### Vitest Test Failure Output Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/learn/debugging-tests.md Example of a failed test output showing the assertion error, diff, and the specific line of code that failed. ```text FAIL src/user.test.js > createUser > sets the default role AssertionError: expected { name: 'Alice', role: 'viewer' } to deeply equal { name: 'Alice', role: 'member' } - Expected + Received { "name": "Alice", - "role": "member", + "role": "viewer", } ❯ src/user.test.js:8:22  6| test('sets the default role', () => {  7| const user = createUser('Alice')  8| expect(user).toEqual({ name: 'Alice', role: 'member' }) ^  9| })  10| }) ``` -------------------------------- ### Start Jaeger and run Vitest with OpenTelemetry Source: https://github.com/vitest-dev/vitest/blob/main/examples/opentelemetry/README.md Starts the Jaeger trace collection service via Docker Compose and executes Vitest with the --experimental.openTelemetry.enabled flag. Shows how to use the default OTLP HTTP exporter, switch to the console exporter for local debugging, or enable browser mode. ```sh # Start Jaeger service to receive otlp traces over http # and serve Web UI at http://localhost:16686 docker compose up -d # Run tests (exports with OTLP HTTP by default) pnpm test --experimental.openTelemetry.enabled # Use console exporter for quick debugging OTEL_TRACES_EXPORTER=console pnpm test --experimental.openTelemetry.enabled # Run browser mode pnpm test --experimental.openTelemetry.enabled --browser.enabled ``` -------------------------------- ### 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') } ``` ``` -------------------------------- ### Select coverage provider in vitest.config.ts Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/coverage.md Set test.coverage.provider to 'v8' or 'istanbul' to choose the coverage tool. v8 is used by default; Vitest prompts to install the matching support package when the process starts. ```typescript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { coverage: { provider: 'v8' // or 'istanbul' }, }, }) ``` -------------------------------- ### Minimize Garbage Collection Noise in Benchmarks Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/benchmarking.md Pre-allocate data in a setup hook to avoid large allocations inside the benchmark loop. Allocating memory during iterations introduces GC noise that can skew computation measurements. ```ts test('sorting', async ({ bench }) => { const original = Array.from({ length: 10000 }, () => Math.random()) let data: number[] // BAD: allocates a new array every iteration, GC adds noise await bench('sort', () => { const data = Array.from({ length: 10000 }, () => Math.random()) data.sort() }).run() // GOOD: pre-allocate, copy in beforeEach await bench( 'sort', () => { data.sort() }, { beforeEach() { data = [...original] }, }, ).run() }) ``` -------------------------------- ### 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) }) ``` -------------------------------- ### Start browser-mode Vitest server Source: https://github.com/vitest-dev/vitest/blob/main/packages/ui/CONTRIBUTING.md Starts a browser-mode Vitest server for developing Browser Mode UI features. This server provides browser runner state to the UI dev server. ```bash pnpm -C packages/ui test:ui --ui --open=false ``` -------------------------------- ### toMatchScreenshot Usage Examples Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/assertions.md TypeScript examples showing basic usage, custom name, options, and both name and options for toMatchScreenshot. Use these patterns to configure visual regression tests. ```typescript // basic usage, auto-generates screenshot name await expect.element(getByTestId('button')).toMatchScreenshot() // with custom name await expect.element(getByTestId('button')).toMatchScreenshot('fancy-button') // with options await expect.element(getByTestId('button')).toMatchScreenshot({ comparatorName: 'pixelmatch', comparatorOptions: { allowedMismatchedPixelRatio: 0.01, }, }) // with both name and options await expect.element(getByTestId('button')).toMatchScreenshot('fancy-button', { comparatorName: 'pixelmatch', comparatorOptions: { allowedMismatchedPixelRatio: 0.01, }, }) ``` -------------------------------- ### Run Node and browser tests with projects in vitest.config.ts Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Use the projects option to define separate configurations for Node-based and browser-based testing strategies. The include patterns shown are examples of file-based conventions you don't have to follow. ```ts import { defineConfig } from 'vitest/config' import { playwright } from '@vitest/browser-playwright' export default defineConfig({ test: { projects: [ { test: { // an example of file based convention, // you don't have to follow it include: [ 'tests/unit/**/*.{test,spec}.ts', 'tests/**/*.unit.{test,spec}.ts', ], name: 'unit', environment: 'node', }, }, { test: { // an example of file based convention, // you don't have to follow it include: [ 'tests/browser/**/*.{test,spec}.ts', 'tests/**/*.browser.{test,spec}.ts', ], name: 'browser', browser: { enabled: true, provider: playwright(), instances: [ { browser: 'chromium' }, ], }, }, }, ], }, }) ``` -------------------------------- ### 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')) ``` ``` -------------------------------- ### Start UI dev server with custom browser runner port Source: https://github.com/vitest-dev/vitest/blob/main/packages/ui/CONTRIBUTING.md Starts the UI dev server in browser preview mode when Vitest prints a browser runner port other than 23315. Pass the port via BROWSER_DEV_PORT. ```bash BROWSER_DEV_PORT=63316 BROWSER_DEV=true pnpm -C packages/ui dev:client ``` -------------------------------- ### Initialize browser mode with vitest init browser (yarn) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs required dependencies and creates browser configuration automatically. Run with yarn. ```bash yarn exec vitest init browser ``` -------------------------------- ### Example traceTimeline failure output Source: https://github.com/vitest-dev/vitest/blob/main/docs/config/experimental.md Shows the timeline printed under a failing test when traceTimeline is enabled, listing each wait step with start, duration, and location. The message option of expect.poll, vi.waitFor, and vi.waitUntil names the step, as with 'user saved (vi.waitUntil)'. ```text FAIL src/search.test.ts > finds new user in search AssertionError: expected [] to have a length of 1 but got +0 - Expected + Received - 1 + 0  ❯ src/search.test.ts:8:50  6| await api.post('/users', { name: 'alice' })  7| await vi.waitUntil(() => db.users.findByName('alice'), { message: 'user saved' })  8| await expect.poll(() => search.query('alice')).toHaveLength(1)  | ^  9| }) Caused by: Error: Matcher did not succeed in time. Trace:  step start duration location vi.waitFor() +2ms 120ms src/search.test.ts:5:12 user saved (vi.waitUntil) +171ms 42ms src/search.test.ts:7:12  expect.poll().toHaveLength() +214ms 1001ms src/search.test.ts:8:50 ``` -------------------------------- ### Example trace timeline output for a failed test Source: https://github.com/vitest-dev/vitest/blob/main/docs/blog/vitest-5-1.md Shows the step timeline printed under a failing assertion, listing each wait step with start, duration, and location. The failing expect.poll().toHaveLength() step is highlighted in the trace. ```text FAIL src/search.test.ts > finds new user in search AssertionError: expected [] to have a length of 1 but got +0 - Expected + Received - 1 + 0  ❯ src/search.test.ts:8:50  6| await api.post('/users', { name: 'alice' })  7| await vi.waitUntil(() => db.users.findByName('alice'), { message: 'user saved' })  8| await expect.poll(() => search.query('alice')).toHaveLength(1)  | ^  9| }) Caused by: Error: Matcher did not succeed in time. Trace:  step start duration location vi.waitFor() +2ms 120ms src/search.test.ts:5:12 user saved (vi.waitUntil) +171ms 42ms src/search.test.ts:7:12  expect.poll().toHaveLength() +214ms 1001ms src/search.test.ts:8:50 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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] }, ], }, }, }) ``` -------------------------------- ### Initialize browser mode with vitest init browser (pnpm) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs required dependencies and creates browser configuration automatically. Run with pnpm. ```bash pnpx vitest init browser ``` -------------------------------- ### Install WebdriverIO provider (bun) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest and @vitest/browser-webdriverio to run tests locally using the WebDriver protocol. ```bash bun add -D vitest @vitest/browser-webdriverio ``` -------------------------------- ### 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() {} } ``` -------------------------------- ### Install WebdriverIO provider (pnpm) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest and @vitest/browser-webdriverio to run tests locally using the WebDriver protocol. ```bash pnpm add -D vitest @vitest/browser-webdriverio ``` -------------------------------- ### query examples that throw Source: https://github.com/vitest-dev/vitest/blob/main/docs/api/browser/locators.md These locators throw because multiple elements match the selector. ```typescript // returns multiple elements page.getByText('Hello').query() // ❌ page.getByText(/^Hello/).query() // ❌ ``` -------------------------------- ### 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 ``` -------------------------------- ### Install WebdriverIO provider (npm) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest and @vitest/browser-webdriverio to run tests locally using the WebDriver protocol. ```bash npm install -D vitest @vitest/browser-webdriverio ``` -------------------------------- ### Install WebdriverIO provider (yarn) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest, vite and @vitest/browser-webdriverio to run tests locally using the WebDriver protocol. ```bash yarn add -D vitest vite @vitest/browser-webdriverio ``` -------------------------------- ### Install @vitest/coverage-istanbul manually Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/coverage.md Manually install the Istanbul coverage support package with npm. Use this instead of relying on the automatic install prompt. ```bash npm i -D @vitest/coverage-istanbul ``` -------------------------------- ### Install @vitest/coverage-v8 manually Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/coverage.md Manually install the V8 coverage support package with npm. Use this instead of relying on the automatic install prompt. ```bash npm i -D @vitest/coverage-v8 ``` -------------------------------- ### Install Playwright provider (bun) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest and @vitest/browser-playwright. Playwright supports parallel execution, making tests run faster. ```bash bun add -D vitest @vitest/browser-playwright ``` -------------------------------- ### 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') } ``` -------------------------------- ### Install Playwright provider (pnpm) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest and @vitest/browser-playwright. Playwright supports parallel execution, making tests run faster. ```bash pnpm add -D vitest @vitest/browser-playwright ``` -------------------------------- ### Install Playwright provider (npm) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest and @vitest/browser-playwright. Playwright supports parallel execution, making tests run faster. ```bash npm install -D vitest @vitest/browser-playwright ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 } }) ``` -------------------------------- ### Install Playwright provider (yarn) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest, vite and @vitest/browser-playwright. Playwright supports parallel execution, making tests run faster. ```bash yarn add -D vitest vite @vitest/browser-playwright ``` -------------------------------- ### Manually install preview provider (bun) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest and @vitest/browser-preview for the preview provider. To run tests in CI you need playwright or webdriverio instead. ```bash bun add -D vitest @vitest/browser-preview ``` -------------------------------- ### Manually install preview provider (pnpm) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest and @vitest/browser-preview for the preview provider. To run tests in CI you need playwright or webdriverio instead. ```bash pnpm add -D vitest @vitest/browser-preview ``` -------------------------------- ### 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, using the same filters the CLI supports. This method is called automatically by startVitest if config.mergeReports and config.standalone are not set. ```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 the test files; these are the same filters that CLI supports. ### Response Returns a `Promise`. ```ts function start(filters?: string[]): Promise ``` ``` -------------------------------- ### Manually install preview provider (yarn) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest, vite and @vitest/browser-preview for the preview provider. To run tests in CI you need playwright or webdriverio instead. ```bash yarn add -D vitest vite @vitest/browser-preview ``` -------------------------------- ### deps.interopDefault TypeError example Source: https://github.com/vitest-dev/vitest/blob/main/docs/config/deps.md Example of runtime TypeErrors that may occur when this feature is disabled. ```text TypeError: createAsyncThunk is not a function TypeError: default is not a function ``` -------------------------------- ### 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 ``` -------------------------------- ### Configuring and running snapshots with SnapshotClient and SnapshotManager Source: https://github.com/vitest-dev/vitest/blob/main/packages/snapshot/README.md Sets up SnapshotClient with a custom equality checker, NodeSnapshotEnvironment, and test run lifecycle methods. Demonstrates asserting file and inline snapshots, completing a run, and aggregating results using SnapshotManager. ```javascript import { SnapshotClient } from '@vitest/snapshot' import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment' import { SnapshotManager } from '@vitest/snapshot/manager' const client = new SnapshotClient({ // you need to provide your own equality check implementation if you use it // this function is called when `.toMatchSnapshot({ property: 1 })` is called isEqual: (received, expected) => equals(received, expected, [iterableEquality, subsetEquality]), }) // class that implements snapshot saving and reading // by default uses fs module, but you can provide your own implementation depending on the environment const environment = new NodeSnapshotEnvironment() // you need to implement this yourselves, // this depends on your runner function getCurrentFilepath() { return '/file.spec.js' } function getCurrentTestName() { return 'test1' } // example for inline snapshots, nothing is required to support regular snapshots, // just call `assert` with `isInline: false` function wrapper(received) { function __INLINE_SNAPSHOT__(inlineSnapshot, message) { client.assert({ received, message, isInline: true, inlineSnapshot, filepath: getCurrentFilepath(), name: getCurrentTestName(), }) } return { // the name is hard-coded, it should be inside another function, so Vitest can find the actual test file where it was called (parses call stack trace + 2) // you can override this behaviour in SnapshotState's `_inferInlineSnapshotStack` method by providing your own SnapshotState to SnapshotClient constructor toMatchInlineSnapshot: (...args) => __INLINE_SNAPSHOT__(...args), } } const options = { updateSnapshot: 'new', snapshotEnvironment: environment, } await client.startCurrentRun( getCurrentFilepath(), getCurrentTestName(), options ) // this will save snapshot to a file which is returned by "snapshotEnvironment.resolvePath" client.assert({ received: 'some text', isInline: false, }) // uses "pretty-format", so it requires quotes // also naming is hard-coded when parsing test files wrapper('text 1').toMatchInlineSnapshot() wrapper('text 2').toMatchInlineSnapshot('"text 2"') const result = await client.finishCurrentRun() // this saves files and returns SnapshotResult // you can use manager to manage several clients const manager = new SnapshotManager(options) manager.add(result) // do something // and then read the summary console.log(manager.summary) ``` -------------------------------- ### 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 ``` -------------------------------- ### Configure global setup and teardown functions Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/lifecycle.md Runs once in the main process before test workers are created and after all tests finish. Use project.provide to share data across tests since tests run in a separate global scope. ```ts export function setup(project) { // Runs once before all tests console.log('Global setup') // Share data with tests project.provide('apiUrl', 'http://localhost:3000') } export function teardown() { // Runs once after all tests console.log('Global teardown') } ``` -------------------------------- ### Manually install preview provider (npm) Source: https://github.com/vitest-dev/vitest/blob/main/docs/guide/browser/index.md Installs vitest and @vitest/browser-preview for the preview provider, which only previews how tests look. To run tests in CI you need playwright or webdriverio instead. ```bash npm install -D vitest @vitest/browser-preview ``` -------------------------------- ### Run all test suites Source: https://github.com/vitest-dev/vitest/blob/main/CONTRIBUTING.md Run this command to execute the entire test suite, including all packages. ```shell pnpm run test:ci ```