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

browser options completeness

24 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

File handling commands in browser tests

Vitest exposes readFile, writeFile, and removeFile APIs for handling files in browser tests. Since Vitest 3.2, all paths are resolved relative to the project root (process.cwd() by default). Previously paths were resolved relative to the test file. By default, Vitest uses utf-8 encoding but this can be overridden with options.

File commands security restrictions

The built-in file commands readFile, writeFile, and removeFile follow Vite's server.fs restrictions for security reasons. writeFile and removeFile require write access through api.allowWrite configuration.

CDP session availability in browser tests

Vitest exposes access to raw Chrome DevTools Protocol via the cdp method exported from vitest/browser. CDP session works only with playwright provider and only when using chromium browser. CDP is available only when browser API write and exec operations are enabled through api.allowWrite and api.allowExec.

Custom commands configuration

Custom commands can be added via the browser.commands config option. Custom functions will override built-in ones if they have the same name. Custom commands run in the Vitest Node process and are callable from browser test code through Vitest's browser RPC connection.

Custom commands security considerations

Custom commands can access local files, environment variables, network services, databases, shell commands, and other Node APIs. Unlike built-in file commands, custom commands do not automatically inherit server.fs protections. Custom commands accepting browser-provided input must validate that input before using it for reading, writing, deleting, executing, or exposing local resources. Use isFileLoadingAllowed from vitest/node for file access validation and require explicit mutation policies like api.allowWrite for writes and api.allowExec for command execution.

Custom commands trace marker recording

Custom commands can record trace markers for the test that triggered them through context.mark. This is the server-side equivalent of page.mark and helps annotate the trace view with custom actions. context.mark is a no-op when browser tracing is not enabled or no test is currently running in the session.

Playwright-specific command context properties

For playwright provider commands, the context object provides: page references the full page containing the test iframe; frame is an async method resolving to a playwright Frame with similar API but limited methods; iframe is a FrameLocator that should be preferred for querying elements because it is more stable and faster; context refers to the unique BrowserContext.

WebdriverIO-specific command context properties

For webdriverio provider commands, the context object provides: browser is the WebdriverIO.Browser API. Vitest automatically switches the webdriver context to the test iframe by calling browser.switchFrame before the command is called, so $ and $$ methods refer to iframe elements, but non-webdriver APIs still refer to the parent frame context.

File handling commands example

Example showing file handling in browser tests: ```ts import { server } from 'vitest/browser' const { readFile, writeFile, removeFile } = server.commands it('handles files', async () => { const file = './test.txt' await writeFile(file, 'hello world') const content = await readFile(file) expect(content).toBe('hello world') await removeFile(file) }) ```

CDP session usage example

Example showing CDP session usage in browser tests: ```ts import { cdp } from 'vitest/browser' const input = document.createElement('input') document.body.appendChild(input) input.focus() await cdp().send('Input.dispatchKeyEvent', { type: 'keyDown', text: 'a', }) expect(input).toHaveValue('a') ```

userEvent API methods signature

The userEvent object exported from 'vitest/browser' provides the following methods for user interactions: setup() returns UserEvent, cleanup() returns Promise<void>, click(element: Element, options?: UserEventClickOptions) returns Promise<void>, dblClick(element: Element, options?: UserEventDoubleClickOptions) returns Promise<void>, tripleClick(element: Element, options?: UserEventTripleClickOptions) returns Promise<void>, selectOptions(element: Element, values: HTMLElement | HTMLElement[] | string | string[], options?: UserEventSelectOptions) returns Promise<void>, keyboard(text: string) returns Promise<void>, type(element: Element, text: string, options?: UserEventTypeOptions) returns Promise<void>, clear(element: Element) returns Promise<void>, tab(options?: UserEventTabOptions) returns Promise<void>, hover(element: Element, options?: UserEventHoverOptions) returns Promise<void>, unhover(element: Element, options?: UserEventHoverOptions) returns Promise<void>, fill(element: Element, text: string, options?: UserEventFillOptions) returns Promise<void>, dragAndDrop(source: Element, target: Element, options?: UserEventDragAndDropOptions) returns Promise<void>. The support is implemented by the browser provider (playwright or webdriverio), with fallback to simulated events via @testing-library/user-event when using preview provider.

page.viewport method

The page.viewport(width: number, height: number) method changes the size of the iframe's viewport and returns Promise<void>.

page.screenshot method overloads

The page object exports two screenshot method overloads: screenshot(options?: ScreenshotOptions) returns Promise<string>, and screenshot(options: Omit<ScreenshotOptions, 'base64'> & { base64: true }) returns Promise<{ path: string; base64: string }>. The screenshot method makes a screenshot of the test iframe or a specific element and returns a path to the screenshot file or path and base64. As of version 3.2.0, screenshot will always return a base64 string if save is set to false, and the path is also ignored in that case.

page.mark method signature and usage

The page.mark method has two overloads: mark(name: string, options?: { stack?: string; kind?: BrowserTraceEntryKind }) returns Promise<void>, and mark<T>(name: string, body: () => T | Promise<T>, options?: { stack?: string; kind?: BrowserTraceEntryKind }) returns Promise<T>. It adds a named marker to the trace timeline for the current test. Pass options.stack to override the callsite location in trace metadata, which is useful for wrapper libraries. Pass options.kind to categorize the marker as a specific type, such as 'action'. If a callback is passed, Vitest creates a trace group with this name, runs the callback, and closes the group automatically. This method is useful only when browser.trace is enabled.

page.extend method

The page.extend(methods: Partial<BrowserPage>) method extends the default page object with custom methods and returns BrowserPage.

page.elementLocator method

The page.elementLocator(element: Element) method wraps an HTML element in a Locator. When querying for elements, the search will always return this element.

page.frameLocator method

The page.frameLocator(iframeElement: Locator) method returns a FrameLocator instance that represents the iframe document and works similarly to the page object. The frame locator does not refer to the Iframe HTML element, but to the iframe's document. By default frameLocator does not support querying elements with expect.element() in cross-origin iframes, though interactive methods such as click() work fine. This is different behaviour than Playwright. To work with cross-origin iframes, pass args: ["--disable-web-security"] in launchOptions or create a custom browser command that accesses the iframe on server side. The frameLocator method is currently supported only by the playwright provider.

page locator methods

The page object exports the following locator methods: getByRole(role: ARIARole | string, options?: LocatorByRoleOptions) returns Locator, getByLabelText(text: string | RegExp, options?: LocatorOptions) returns Locator, getByTestId(text: string | RegExp) returns Locator, getByAltText(text: string | RegExp, options?: LocatorOptions) returns Locator, getByPlaceholder(text: string | RegExp, options?: LocatorOptions) returns Locator, getByText(text: string | RegExp, options?: LocatorOptions) returns Locator, getByTitle(text: string | RegExp, options?: LocatorOptions) returns Locator.

cdp function availability

The cdp() function exported from 'vitest/browser' returns the current Chrome DevTools Protocol session (CDPSession). CDP session works only with playwright provider and only when using chromium browser. CDP is a privileged debugging API available only when browser API write and exec operations are enabled through api.allowWrite and api.allowExec.

server export properties

The server export represents the Node.js environment where the Vitest server is running and provides the following properties: platform (Platform type, same as process.platform on the server), version (string, same as process.version on the server), provider (string, name of the browser provider), browser (string, name of the current browser), commands (BrowserCommands, available commands for the browser), config (SerializedConfig, serialized test config).

utils helper functions

The utils object exported from 'vitest/browser' provides utility functions: getElementLocatorSelectors(element: Element) returns LocatorSelectors (similar to page.elementLocator but returns only locator selectors), debug(el?: Element | Locator | null | (Element | Locator)[], maxLength?: number, options?: PrettyDOMOptions) returns void (prints prettified HTML of an element), prettyDOM(dom?: Element | Locator | undefined | null, maxLength?: number, prettyFormatOptions?: PrettyDOMOptions) returns string (returns prettified HTML of an element), configurePrettyDOM(options: StringifyOptions) returns void (configures default options of prettyDOM and debug functions and affects vitest-browser-{framework} package), getElementError(selector: string, container?: Element) returns Error (creates 'Cannot find element' error useful for custom locators).

utils.aria namespace

The utils.aria namespace exposes low-level utilities used by Vitest's ARIA snapshot matchers: generateAriaTree(rootElement: Element) returns AriaNode, renderAriaTree(root: AriaNode) returns string, renderAriaTemplate(template: AriaTemplateNode) returns string, parseAriaTemplate(text: string) returns AriaTemplateNode, matchAriaTree(root: AriaNode, template: AriaTemplateNode) returns { pass: boolean; resolved: string }.

configurePrettyDOM options

The configurePrettyDOM function accepts options with the following properties: maxDepth (Maximum depth to print nested elements, default: Infinity), maxLength (Maximum length of the output string, default: 7000), filterNode (A CSS selector string or function to filter out nodes from the output - when a string is provided, elements matching the selector will be excluded; when a function is provided, it should return false to exclude a node), highlight (Enable syntax highlighting, default: true), and other options from @vitest/pretty-format.

commands API export

The commands export from 'vitest/browser' provides available commands for the browser and is a shortcut to server.commands, which returns BrowserCommands.

Give your agent this brain