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 · API reference · all subjects

vitest-browser-react

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

custom locators with locators.extend

Example showing custom locators: import { locators } from 'vitest/browser'; import { render } from 'vitest-browser-react'; locators.extend({ getByArticleTitle(title) { return `[data-title="${title}"]`; } }); const screen = await render(<Component />); await expect.element(screen.getByArticleTitle('Hello World')).toBeVisible();

configure reactStrictMode example

Example showing configure usage: import { configure } from 'vitest-browser-react/pure'; configure({ reactStrictMode: true, });

render container option example

Example showing custom container: const table = document.createElement('table'); const { container } = await render(<TableBody {...props} />, { container: document.body.appendChild(table), });

render function signature

The render function is async and takes a React.ReactNode UI element and optional ComponentRenderOptions. It returns a Promise<RenderResult>. Example: const screen = await render(<Component />). Note that render is asynchronous, unlike in other packages, to support Suspense correctly.

render result: container property

The container property is the containing div DOM node of the rendered React element. It is a regular DOM node and technically supports querySelector. However, using container to query elements is discouraged—use the provided locators instead as they are more resilient to component changes.

render result: locator property

The locator property is a locator of the container. It is useful for queries scoped only to your component or for passing to other assertions: await expect.element(locator).toHaveTextContent('Hello World').

render result: rerender method signature

The rerender method has signature: function rerender(ui: React.ReactNode): Promise<void>. It re-renders the same component with different props and records a react.rerender trace mark in the Trace View. It is better to test the component that's doing prop updating rather than relying on rerender.

render result: unmount method signature

The unmount method has signature: function unmount(): Promise<void>. It unmounts the rendered component and records a react.unmount trace mark in the Trace View. After unmount, container.innerHTML is empty. This is useful for testing cleanup behavior and ensuring no event handlers are left hanging.

render result: asFragment method signature

The asFragment method has signature: function asFragment(): DocumentFragment. It returns a DocumentFragment of the rendered component, useful for avoiding live bindings and seeing how the component reacts to events.

renderHook function signature

The renderHook function has signature: export function renderHook<Props, Result>(renderCallback: (initialProps?: Props) => Result, options: RenderHookOptions<Props>): Promise<RenderHookResult<Result, Props>>. It is a convenience wrapper around render with a custom test component, emerged from a popular testing pattern.

renderHook options: initialProps

The initialProps option declares the props that are passed to the render callback when first invoked. These will not be passed if you call rerender without props. When using renderHook with wrapper and initialProps, the initialProps are not passed to the wrapper component.

renderHook result: result property

The result property holds the value of the most recently committed return value of the render callback. The value is held in result.current, similar to a ref. This allows you to access the hook's return value in tests.

renderHook result: rerender method

The rerender method on renderHook result re-renders the previously rendered render callback with new props. Example: await rerender({ name: 'Bob' }).

renderHook result: unmount method

The unmount method on renderHook result unmounts the test hook. Example: await unmount().

render trace mark recording

The render function records a react.render trace mark visible in the Trace View. The rerender function records a react.rerender trace mark, and unmount records a react.unmount trace mark.

vitest-browser-react entry points

The package exposes two entry points: vitest-browser-react and vitest-browser-react/pure. They expose almost identical API, with pure also exposing configure. The pure entry point does not add a handler to remove the component before the next test, while the main entry point does.

configure function for React Strict Mode

The configure method is available from vitest-browser-react/pure and accepts options to configure component rendering. It has a reactStrictMode option (disabled by default) that can be set to true to render the component in React Strict Mode.

vitest-browser-react benefits over @testing-library/react

vitest-browser-react provides benefits unique to Browser Mode: it returns APIs that interact well with built-in locators, user events, and assertions. Vitest automatically retries the element until assertions are successful, even if the component was rerendered between assertions.

render example with component props

Example showing render usage: import { render } from 'vitest-browser-react'; import { expect, test } from 'vitest'; import Component from './Component.jsx'; test('counter button increments the count', async () => { const screen = await render(<Component count={1} />); await screen.getByRole('button', { name: 'Increment' }).click(); await expect.element(screen.getByText('Count is 2')).toBeVisible(); });

render options: wrapper

The wrapper option accepts a React Component that will be rendered around the inner element. This is useful for wrapping the component with data providers or other context providers. Example: Pass wrapper: AllTheProviders where AllTheProviders renders providers like ThemeProvider or TranslationProvider around the children prop.

render wrapper option example

Example showing wrapper usage: function AllTheProviders({ children }) { return <ThemeProvider theme="light"><TranslationProvider>{children}</TranslationProvider></ThemeProvider>; } export function customRender(ui, options) { return render(ui, { wrapper: AllTheProviders, ...options }); }

renderHook example with useState

Example showing renderHook usage: const { result } = await renderHook(() => { const [name, setName] = useState(''); React.useEffect(() => { setName('Alice'); }, []); return name; }); expect(result.current).toBe('Alice');

renderHook initialProps example

Example showing initialProps: const { rerender } = await renderHook(({ name = 'Alice' } = {}) => name, { initialProps: { name: 'Alice' }, }); expect(result.current).toEqual({ name: 'Alice' }); await rerender(); expect(result.current).toEqual({ name: undefined });

Testing snippets with wrapper components

For simple snippets, use a wrapper component with dummy children to test them. Setting data-testid attributes can be helpful when testing slots. Render the wrapper component and query for the child elements using getByTestId or other locators.

cleanup function signature

The cleanup function signature is: export function cleanup(): void. It removes all components rendered with render.

vitest-browser-svelte package overview

vitest-browser-svelte is a community package that renders Svelte components in Browser Mode. It provides APIs that interact well with built-in locators, user events, and assertions. Vitest automatically retries elements until assertions are successful, even if the component was rerendered between assertions.

vitest-browser-svelte entry points

The package exposes two entry points: 'vitest-browser-svelte' and 'vitest-browser-svelte/pure'. They expose identical API, but the 'pure' entry point does not add a handler to remove the component before the next test starts.

render function signature

The render function signature is: export function render<C extends Component>(Component: ComponentImport<C>, options?: ComponentOptions<C>, renderOptions?: SetupOptions): Promise<RenderResult<C>>. It records a 'svelte.render' trace mark visible in the Trace View.

render function props option

The render function can accept component props directly as options, or within a 'props' property. The newer convention passes props directly: await render(Component, { initialCount: 1 }) instead of { props: { initialCount: 1 } }.

render target option

By default, Vitest creates a div, appends it to document.body, and renders the component there. If you provide your own HTMLElement container via the 'target' option, it will not be appended automatically — you must call document.body.appendChild(container) before render. This is useful when testing elements like tbody that cannot be children of a div.

render baseElement option

The baseElement option can be passed in a third argument to render. If target is specified, baseElement defaults to that; otherwise it defaults to document.body. This is used as the base element for queries and for what is printed when debug() is called.

RenderResult container property

The render function returns a container property which is the containing DOM node where the Svelte component is rendered. It is a regular DOM node and technically supports querySelector calls, but using container to query elements should be avoided in favor of locators which are more resilient to component changes.

RenderResult component property

The render function returns a component property which is the mounted Svelte component instance. This allows access to component methods and properties if needed, including component exports.

RenderResult locator property

The render function returns a locator property which is the locator of the container. This is useful for queries scoped only to the component, or for passing to other assertions.

rerender method signature

The rerender method signature is: function rerender(props: Partial<ComponentProps<T>>): Promise<void>. It updates the component's props and waits for Svelte to apply the changes. Use this to test how your component responds to prop changes. It also records a 'svelte.rerender' trace mark in the Trace View.

unmount method signature

The unmount method signature is: function unmount(): Promise<void>. It unmounts and destroys the Svelte component and records a 'svelte.unmount' trace mark in the Trace View. After unmount, container.innerHTML === ''. This is useful for testing what happens when a component is removed from the page, such as checking that event handlers are properly cleaned up.

Basic svelte-browser-svelte render example

Example showing basic render usage: const screen = await render(Component, { initialCount: 1 }). Then interact with elements using locators: await screen.getByRole('button', { name: 'Increment' }).click() and make assertions: await expect.element(screen.getByText('Count is 2')).toBeVisible().

RenderResult includes all locators

In addition to the documented return value, the render function returns all available locators relative to the baseElement, including custom ones defined via the locators.extend API.

Testing complex snippets with createRawSnippet

For more complex snippets where you want to check arguments, use Svelte's createRawSnippet API. Pass the snippet as a prop to the component being tested: render(Subject, { name: 'Alice', message: createRawSnippet(greeting => ({ render: () => `<span>${greeting()}</span>` })) }).

vitest-browser-vue render function signature

The render function from vitest-browser-vue has the signature: export function render(component: Component, options?: ComponentRenderOptions): Promise<RenderResult>. It renders a Vue component in Browser Mode and records a vue.render trace mark visible in the Trace View.

render function options: container

The container option allows you to specify a custom HTMLElement where the component will be rendered. By default, Vitest creates a div, appends it to document.body, and renders the component there. If you provide a custom container, it will not be appended automatically — you must call document.body.appendChild(container) before render. This is useful when unit testing elements like tbody that cannot be children of a div.

render function options: baseElement

The baseElement option specifies the base element for queries and what is printed when using debug(). If container is specified, baseElement defaults to that; otherwise it defaults to document.body. This is useful for testing portal components that render HTML outside the container div.

render returns all locators relative to baseElement

The render function returns all available locators relative to the baseElement, including custom locators defined via locators.extend(). These can be used directly on the returned screen object, such as screen.getByRole() and screen.getByText().

RenderResult.container property

The container property of RenderResult is the containing DOM node where the Vue component is rendered. It is a regular DOM node and you can call container.querySelector() and similar methods on it. However, using container to query elements should be avoided in favor of using locators, which are more resilient to component changes.

RenderResult.baseElement property

The baseElement property is the containing DOM node where the Vue component is rendered in the container. If not specified in render options, it defaults to document.body. Queries returned by render look into baseElement, allowing you to test portal components without specifying baseElement separately.

RenderResult.locator property

The locator property of RenderResult is a locator of the container. It is useful for scoping queries only to your component or passing it down to other assertions. Example: const { locator } = await render(NumberDisplay, { props: { number: 2 } }); await locator.getByRole('button').click();

RenderResult.debug() method signature

The debug method has the signature: function debug(el?: HTMLElement | HTMLElement[] | Locator | Locator[], maxLength?: number, options?: PrettyDOMOptions): void. It is a shortcut for console.log(prettyDOM(baseElement)) and prints the DOM content of the container or specified elements to the console.

RenderResult.rerender() method

The rerender method has the signature: function rerender(props: Partial<Props>): Promise<void>. It updates the props of a rendered component and records a vue.rerender trace mark in the Trace View. Example: const { rerender } = await render(NumberDisplay, { props: { number: 1 } }); await rerender({ number: 2 });

RenderResult.unmount() method

The unmount method has the signature: function unmount(): Promise<void>. It causes the rendered component to be unmounted and records a vue.unmount trace mark in the Trace View. This is useful for testing what happens when a component is removed from the page, such as ensuring event handlers are cleaned up to prevent memory leaks.

RenderResult.emitted() method

The emitted method has two overloads: function emitted<T = unknown>(): Record<string, T[]> and function emitted<T = unknown[]>(eventName: string): undefined | T[]. It returns the emitted events from the Component. The first overload returns all emitted events as a record; the second returns events for a specific event name.

vitest-browser-vue cleanup function

The cleanup function from vitest-browser-vue has the signature: export function cleanup(): void. It removes all components rendered with render().

vitest-browser-vue entry points

The vitest-browser-vue package exposes two entry points: vitest-browser-vue and vitest-browser-vue/pure. Both expose identical APIs. The pure entry point does not add a handler to remove the component before the next test starts.

render supports all @vue/test-utils mount options

The render function supports all mount options from @vue/test-utils except attachTo (use container instead). In addition, it supports container and baseElement options specific to vitest-browser-vue.

vitest-browser-vue integrates with locators and assertions

vitest-browser-vue returns APIs that interact well with built-in locators, user events, and assertions. Vitest automatically retries the element until the assertion is successful, even if it was rerendered between assertions.

Extend locators in vitest-browser-vue with locators.extend

To extend locator queries in vitest-browser-vue, use the locators.extend API from vitest/browser. Define custom locators to make render return new custom locators. Example: locators.extend({ getByArticleTitle(title) { return `[data-title="${title}"]` } });

Configure Vue Test Utils options via config export

You can configure Vue Test Utils options by assigning properties to the config export (available in both vitest-browser-vue and vitest-browser-vue/pure). Example: import { config } from 'vitest-browser-vue/pure'; config.global.stubs.CustomComponent = { template: '<div></div>' };

vitest-browser-vue render example with Counter component

Example showing how to render a Vue component and test it: import { render } from 'vitest-browser-vue'; import { expect, test } from 'vitest'; import Component from './Component.vue'; test('counter button increments the count', async () => { const screen = await render(Component, { props: { initialCount: 1 } }); await screen.getByRole('button', { name: 'Increment' }).click(); await expect.element(screen.getByText('Count is 2')).toBeVisible(); });

vitest-browser-vue container example with table element

Example showing how to use a custom container when rendering a tbody element: const table = document.createElement('table'); const { container } = await render(TableBody, { props, container: document.body.appendChild(table) });

vitest-browser-vue locator example

Example showing how to use the locator property from render result: const { locator } = await render(NumberDisplay, { props: { number: 2 } }); await locator.getByRole('button').click(); await expect.element(locator).toHaveTextContent('Hello World');

Browser Mode imports moved from @vitest/browser/context to vitest/browser

The context is no longer imported from @vitest/browser/context but from vitest/browser. The old path will keep working until the next major version for compatibility. Example: import { page } from 'vitest/browser'

Give your agent this brain