Vitest Browser React Renderer

2.2.0 · active · verified Sun Apr 19

vitest-browser-react is a testing utility designed to render React components within Vitest's Browser Mode, providing a browser-like environment for component testing. Currently at version 2.2.0, this library receives regular updates, often aligning with Vitest's own release cycle, indicating active maintenance. Its core differentiator lies in its deep integration with Vitest Browser Mode's native locator and retry-ability APIs, offering an ergonomic testing experience without requiring explicit `act` calls for most scenarios. Unlike `@testing-library/react`, it leverages Vitest's built-in browser assertion mechanisms, simplifying asynchronous testing patterns. It also provides a `renderHook` utility for testing React hooks and can automatically inject `page.render` into the Vitest `page` object for convenience.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates rendering a simple React counter component, simulating a user click, and asserting the updated text content using Vitest's built-in browser locators and retry-ability.

import { render } from 'vitest-browser-react';
import { expect, test } from 'vitest';

function Counter({ initialCount = 0 }) {
  const [count, setCount] = useState(initialCount);
  return (
    <div>
      <p>Count is {count}</p>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
    </div>
  );
}

// Simulate useState if React is not directly imported for brevity
let currentCount = 0;
const useState = (initial) => {
  if (currentCount === 0) currentCount = initial;
  const setter = (val) => { currentCount = typeof val === 'function' ? val(currentCount) : val; };
  return [currentCount, setter];
};

test('counter button increments the count', async () => {
  currentCount = 1; // Reset for test clarity
  const screen = await render(<Counter initialCount={1} />);

  await screen.getByRole('button', { name: 'Increment' }).click();

  await expect.element(screen.getByText('Count is 2')).toBeVisible();
});

view raw JSON →