new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vitest · Config reference · all subjects

config/browser

109 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

browser.commands configuration option

The browser.commands configuration option has type Record<string, BrowserCommand> and default value of { readFile, writeFile, ... }. It allows custom commands that can be imported during browser tests from vitest/browser.

browser.commands security considerations

Commands run in the Vitest Node process. If a command exposes filesystem, process, network, database, or shell access based on browser-provided input, you must validate and restrict that input inside the command. Built-in file commands apply Vite server.fs checks and write-access checks, but custom commands are responsible for their own protections.

browser.connectTimeout option

The browser.connectTimeout option has type number with a default value of 60000 milliseconds. It specifies the timeout for the browser to establish a WebSocket connection with the Vitest server. If the connection takes longer than this timeout, the test suite will fail.

browser.dependencySourcemaps disabled disables debugging into dependencies

When dependencySourcemaps is set to false, pausing inside dependency code shows the compiled code the browser actually runs instead of the dependency's original sources. Disabling sourcemaps makes test runs faster because the server doesn't generate and inline the maps, and every browser tab downloads several times fewer bytes.

browser.dependencySourcemaps does not affect reported test errors

Reported test errors are not affected by the dependencySourcemaps setting. When an error is thrown inside a pre-bundled dependency, Vitest maps its stack frames using the sourcemaps stored on disk even when dependencySourcemaps is disabled. Frames from dependencies served without pre-bundling that don't ship their own sourcemaps fall back to the position in the served code.

browser.dependencySourcemaps Vitest pre-built modules never serve sourcemaps in headless runs

Vitest never serves sourcemaps of its own pre-built modules in headless runs unless --inspect is used. Their frames are hidden from stack traces anyway. Sourcemaps of your own source files are always served regardless of the dependencySourcemaps setting.

browser.dependencySourcemaps option

The browser.dependencySourcemaps option is a boolean configuration that defaults to true. It controls whether sourcemaps of dependencies in node_modules are served to the browser during headless test runs.

browser.detailsPanelPosition 'right' behavior

When set to 'right', the details panel shows on the right side with a horizontal split between the browser viewport and the details panel.

browser.detailsPanelPosition 'bottom' behavior

When set to 'bottom', the details panel shows at the bottom with a vertical split between the browser viewport and the details panel.

browser.detailsPanelPosition CLI usage

The browser.detailsPanelPosition option can be configured via CLI using --browser.detailsPanelPosition=bottom or --browser.detailsPanelPosition=right.

browser.detailsPanelPosition configuration example

To set the details panel position to bottom in vitest.config.ts, configure it under test.browser.detailsPanelPosition: 'bottom'. The full example shows: import { defineConfig } from 'vitest/config' export default defineConfig({ test: { browser: { enabled: true, detailsPanelPosition: 'bottom', // or 'right' }, }, })

browser.detailsPanelPosition type and default

The browser.detailsPanelPosition option has type 'right' | 'bottom' with a default value of 'right'. It controls the default position of the details panel in the Vitest UI when running browser tests.

browser.enabled requires provider and instances configuration

To enable Browser Mode, you must also specify the provider configuration option and at least one instance in the instances configuration array. Available providers are playwright, webdriverio, and preview.

browser.enabled makes tests run in browser by default

Enabling the browser.enabled flag makes Vitest run all tests in a browser by default.

browser.enabled CLI flags

The browser.enabled option can be set via CLI using the flags --browser or --browser.enabled=false.

browser.enabled option type and default

The browser.enabled configuration option has type boolean and default value false.

browser.enabled configuration example

Example vitest.config.js showing browser.enabled set to true with playwright provider and a chromium instance: import { defineConfig } from 'vitest/config' import { playwright } from '@vitest/browser-playwright' export default defineConfig({ test: { browser: { enabled: true, provider: playwright(), instances: [ { browser: 'chromium' }, ], }, }, })

browser.headless configuration option

The browser.headless option controls whether the browser runs in headless mode. It is of type boolean, has a default value of process.env.CI, and can be set via CLI using --browser.headless or --browser.headless=false. When running Vitest in CI, it is enabled by default. This option applies to the browser config.

browser.instances purpose

browser.instances defines multiple browser setups. Every config has to have at least a browser field.

browser.instances implementation detail

Under the hood, Vitest transforms instances into separate test projects sharing a single Vite server for better caching performance.

browser.instances available options

The following browser options can be specified in each instance: browser (the name of the browser), headless, locators, viewport, testerHtmlPath, screenshotDirectory, screenshotFailures, and provider. Most project options can also be specified except those marked with a CRoot icon.

browser.instances inheritance from root config

Every browser config in instances inherits options from the root config. For example, if setupFile or testerHtmlPath is defined at the root browser level, each instance will implicitly have those options unless overridden.

browser.instances type and default

The browser.instances option has type BrowserConfig and a default value of an empty array [].

browser.locators.exact configuration option

The browser.locators.exact option controls whether locators match text exactly by default. It is of type boolean with a default value of true. When set to true, locators match text exactly, requiring a full, case-sensitive match. Individual locator calls can override this default via their own exact option.

browser.locators.errorFormat configuration option

The browser.locators.errorFormat option controls what Vitest prints when a locator cannot find an element. It is of type 'html' | 'aria' | 'all' with a default value of 'all'. The 'html' option prints the DOM subtree as HTML using utils.prettyDOM. The 'aria' option prints the DOM subtree as an ARIA snapshot, which focuses on accessible roles, names, and state. The 'all' option prints the ARIA snapshot first, followed by the HTML output. Vitest prints information for the DOM subtree where the locator search ran, or document.body for page-level locators.

browser.locators.errorFormat example configuration

The errorFormat option can be set in the Vitest config file within the test.browser.locators object. Example: export default defineConfig({ test: { browser: { enabled: true, locators: { errorFormat: 'aria', }, }, }, })

browser.locators.exact example usage

The exact option affects how locators match text. With exact: true (default), a locator like page.getByText('Hello, World', { exact: true }) only matches the string 'Hello, World' exactly. With exact: false, it matches variations like 'Hello, World!', 'Say Hello, World', and other strings containing the text.

browser.locators.testIdAttribute configuration option

The browser.locators.testIdAttribute option specifies the HTML attribute used to find elements with the getByTestId locator. It is of type string with a default value of 'data-testid'.

BrowserScript id field usage

The id field is used as an identifier when 'content' is provided and type is 'module'. TypeScript extensions like .ts can be added to the id to give Vite a hint about the file extension.

browser.orchestratorScripts type and default

The browser.orchestratorScripts configuration option has type BrowserScript[] and a default value of an empty array [].

browser.orchestratorScripts purpose

Custom scripts that should be injected into the orchestrator HTML before test iframes are initiated. The orchestrator HTML document sets up iframes and does not actually import the user's code.

BrowserScript interface specification

BrowserScript has the following fields: id (string, optional, default 'injected-${index}.js'), content (string, optional, JavaScript content processed by Vite plugins if type is 'module'), src (string, optional, path to script resolved by Vite), async (boolean, optional, whether script loads asynchronously), type (string, optional, script type with default value 'module').

BrowserScript content field processing

The content field contains JavaScript code to be injected. This string is processed by Vite plugins if type is 'module'. The id field can be used to give Vite a hint about the file extension.

BrowserScript src field resolution

The src field specifies the path to the script. This value is resolved by Vite so it can be a node module or a file path.

browser.expect.toMatchScreenshot.screenshotDirectory option

The screenshotDirectory option under browser.expect.toMatchScreenshot has type string | undefined with default value __screenshots__. It specifies the directory name used for storing reference screenshots. This value is passed to resolveScreenshotPath and resolveDiffPath functions and used in the default path resolution of resolveScreenshotPath.

browser.expect configuration option

The browser.expect configuration option has type ExpectOptions and defines default options for browser-related assertions, specifically the toMatchScreenshot assertion.

Comparator options must be optional with defaults

When implementing custom comparators, comparator options must always be optional with default values since the options parameter in toMatchScreenshot is optional and users might not provide all comparator options.

Respect createDiff flag for comparator performance

The createDiff flag in comparator options indicates whether a diff image is needed. During stable screenshot detection, Vitest calls comparators with createDiff: false to avoid unnecessary work. Comparators should respect this flag to keep tests fast.

resolveScreenshotPath example grouping by browser

Example of resolveScreenshotPath function to group screenshots by browser: ```ts resolveScreenshotPath: ({ arg, browserName, ext, root, testFileName }) => `${root}/screenshots/${browserName}/${testFileName}/${arg}${ext}` ```

toMatchScreenshot ext parameter behavior

The ext parameter in toMatchScreenshot resolveScreenshotPath is the screenshot extension with leading dot. It can be set through arguments passed to toMatchScreenshot but falls back to '.png' if an unsupported extension is used.

toMatchScreenshot arg parameter behavior

The arg parameter in toMatchScreenshot resolveScreenshotPath is the path without extension, sanitized and relative to the test file. It comes from the arguments passed to toMatchScreenshot; if called without arguments it is auto-generated. When toMatchScreenshot is called with no arguments the arg is auto-generated (e.g., 'calls-onclick-1'). When called with 'foo/bar/baz.png' the arg is 'foo/bar/baz'. When called with '../foo/bar/baz.png' the arg is 'foo/bar/baz' (normalized).

Custom comparator registration and usage example

Example of registering and using a custom comparator named myCustomComparator: ```ts import { defineConfig } from 'vitest/config' // 1. Declare the comparator's options type declare module 'vitest/browser' { interface ScreenshotComparatorRegistry { myCustomComparator: { sensitivity?: number ignoreColors?: boolean } } } // 2. Implement the comparator export default defineConfig({ test: { browser: { expect: { toMatchScreenshot: { comparators: { myCustomComparator: async ( reference, actual, { createDiff, // always provided by Vitest sensitivity = 0.01, ignoreColors = false, } ) => { // ...algorithm implementation return { pass, diff, message } }, }, }, }, }, }, }) ``` Then use it in tests: `await expect(locator).toMatchScreenshot({ comparatorName: 'myCustomComparator', comparatorOptions: { sensitivity: 0.08, ignoreColors: true } })`

resolveDiffPath example storing diffs in subdirectory

Example of resolveDiffPath function to store diffs in a subdirectory of attachments: ```ts resolveDiffPath: ({ arg, attachmentsDir, browserName, ext, root, testFileName }) => `${root}/${attachmentsDir}/screenshot-diffs/${testFileName}/${arg}-${browserName}${ext}` ```

toMatchScreenshot configuration example with pixelmatch comparator

Example configuration for toMatchScreenshot with pixelmatch comparator and custom screenshot path resolution: ```ts import { defineConfig } from 'vitest/config' export default defineConfig({ test: { browser: { enabled: true, expect: { toMatchScreenshot: { comparatorName: 'pixelmatch', comparatorOptions: { threshold: 0.2, allowedMismatchedPixels: 100, }, resolveScreenshotPath: ({ arg, browserName, ext, testFileName }) => `custom-screenshots/${testFileName}/${arg}-${browserName}${ext}`, }, }, }, }, }) ```

Comparator function signature and behavior

A Comparator function has the signature: type Comparator<Options> = (reference: { metadata: { height: number; width: number }, data: TypedArray }, actual: { metadata: { height: number; width: number }, data: TypedArray }, options: { createDiff: boolean } & Options) => Promise<{ pass: boolean, diff: TypedArray | null, message: string | null }> | { pass: boolean, diff: TypedArray | null, message: string | null }. Reference and actual images are decoded as PNG. The data property is a flat TypedArray (Buffer, Uint8Array, or Uint8ClampedArray) containing pixel data in RGBA format: 4 bytes per pixel (red, green, blue, alpha from 0 to 255 each), row-major order (pixels left-to-right, top-to-bottom), total length is width × height × 4 bytes, and the alpha channel is always present with images without transparency having alpha values set to 255 (fully opaque). The createDiff option indicates whether a diff image is needed; during stable screenshot detection Vitest calls comparators with createDiff: false to avoid unnecessary work.

browser.expect.toMatchScreenshot.comparators option

The comparators option under browser.expect.toMatchScreenshot has type Record<string, Comparator>. It registers custom screenshot comparison algorithms like SSIM or other perceptual similarity metrics.

browser.expect.toMatchScreenshot.resolveDiffPath option

The resolveDiffPath option under browser.expect.toMatchScreenshot has type (data: PathResolveData) => string. Its default output is path.resolve(root, attachmentsDir, testFileDirectory, testFileName, `${arg}-${browserName}-${platform}${ext}`). This function customizes where diff images are stored when screenshot comparisons fail. It receives the same data object as resolveScreenshotPath.

browser.expect.toMatchScreenshot.resolveScreenshotPath option

The resolveScreenshotPath option under browser.expect.toMatchScreenshot has type (data: PathResolveData) => string. Its default output is path.resolve(root, testFileDirectory, screenshotDirectory, testFileName, `${arg}-${browserName}-${platform}${ext}`). This function customizes where reference screenshots are stored and receives an object with properties: arg (path without extension, sanitized and relative to test file), ext (screenshot extension with leading dot), browserName (browser name), platform (Node.js platform), screenshotDirectory (directory name for screenshots), root (absolute path to project root), testFileDirectory (path to test file relative to project root), testFileName (test filename), testName (test name including parent describe blocks, sanitized), attachmentsDir (attachments directory value), and project (TestProject the test belongs to, experimental as of 4.1.6).

preview provider limitation: no CDP or low-level browser interactions

The preview provider does not support CDP (Chrome DevTools Protocol) commands or other low-level browser interactions. The userEvent API is re-exported from @testing-library/user-event and does not have special integration with the browser.

preview provider installation and setup

To use the preview browser provider, install the @vitest/browser-preview npm package and import the preview export from it. Then configure it in the test.browser.provider property of your Vitest config file.

preview provider basic configuration example

Example Vitest configuration using the preview provider: ```ts import { preview } from '@vitest/browser-preview' import { defineConfig } from 'vitest/config' export default defineConfig({ test: { browser: { provider: preview(), instances: [{ browser: 'chromium' }] }, }, }) ``` This opens a browser window using the default browser to run tests. Configure which browser to use by setting the browser property in the instances array.

preview provider limitation: no headless mode

The preview provider does not support headless mode. The browser window will always be visible when running tests.

preview provider limitation: no multiple instances of same browser

The preview provider does not support multiple instances of the same browser. Each instance must use a different browser.

preview provider limitation: browser options

The preview provider does not support advanced browser capabilities or options. You can only specify the browser name in the instances configuration.

preview provider manual browser opening

Vitest will attempt to open the configured browser automatically, but this may not work in all environments. If automatic opening fails, you can manually open the provided URL in your desired browser.

contextOptions configure browser context creation

Vitest creates a new context for every test file by calling browser.newContext(). You can configure this behaviour by specifying custom arguments. Vitest always sets ignoreHTTPSErrors to true and serviceWorkers to 'allow' to support module mocking via MSW. It is recommended to use test.browser.viewport instead of specifying it in contextOptions.

Context isolation in Vitest Playwright

Unlike Playwright test runner, Vitest opens a single page to run all tests that are defined in the same file. This means isolation is restricted to a single test file, not to every individual test. A new context is created for every test file, not every test.

Playwright provider accepts launchOptions, connectOptions, and contextOptions

When calling playwright(), you can configure launchOptions, connectOptions, and contextOptions at the top level or inside instances. These options can be shared between all instances or overridden for individual instances. When overriding options for a single instance, they will NOT merge with the parent options.

Basic Playwright provider configuration example

import { playwright } from '@vitest/browser-playwright' import { defineConfig } from 'vitest/config' export default defineConfig({ test: { browser: { provider: playwright(), instances: [{ browser: 'chromium' }] }, }, }) This example shows how to configure the Playwright provider with a single Chromium browser instance.

Install @vitest/browser-playwright package

To run tests using Playwright, you need to install the @vitest/browser-playwright npm package and specify its playwright export in the test.browser.provider property of your config.

Give your agent this brain