Vitest 26 🧪 Component Testing — vitest-browser-react and Framework Renderers
Component testing sits between unit testing and end-to-end testing. A unit test exercises a pure function; an end-to-end test drives a real browser against a running application. A component test mounts a single component in a real browser, renders it, interacts with it through the DOM, and asserts on what the user would see. Vitest’s browser mode makes this possible by running tests inside a real browser through the Playwright provider, and the vitest-browser-react package is the official renderer that connects React components to that browser context.
The move to browser mode is a response to a specific limitation of jsdom. The jsdom environment simulates the DOM in Node, but it does not implement layout, it does not run real CSS, and it cannot exercise the browser’s event loop the way a real browser does. Component tests that depend on visibility, scroll, focus, or the native event system need a real browser, and Vitest’s browser mode provides one. The trade-off is that browser mode is heavier: it launches a browser, it is slower per test, and it requires the Playwright provider and its browser binaries.
This chapter covers the browser mode configuration, the vitest-browser-react renderer, the user-event API for interactions, and the locator-based queries that replace the testing-library helpers. The sections walk through the provider setup, the render and interaction pattern, and the migration from jsdom-based tests to browser-based ones.
Key point: Browser mode runs component tests in a real browser through Playwright, and vitest-browser-react renders a React component into that browser with a render function that returns locators; the locators replace the old testing-library queries, and the user-event API replaces fireEvent, so the test drives the component the way a real user would.
Why browser mode exists
The jsdom fidelity problem. jsdom is a JavaScript reimplementation of the DOM, and it is excellent at what it does, but it is not a browser. It has no layout engine, so getBoundingClientRect returns zeros, offsetWidth is zero, and any component that measures itself cannot be tested meaningfully. It has no CSS cascade, so a test cannot assert that a class change actually makes an element visible or hidden. The browser mode solves the fidelity problem by running the test in a real browser that has all of these things.
The event system problem. The testing-library fireEvent dispatches synthetic events, and it does not run the browser’s real event pipeline. A component that relies on focus and blur ordering, on pointer events, on the composition events of an IME, or on the browser’s native form validation cannot be tested with synthetic events. The user-event API in browser mode drives the real browser input pipeline, so the component sees the same events a real user would generate.
The debugging problem. A test failure in jsdom produces a stack trace, and the developer has to reconstruct what the DOM looked like. Browser mode can run in headed mode, and the test can pause with page.pause() so the developer sees the real browser at the failure point. The browser’s devtools are available, and the network panel and the console are the real ones.
The snapshot problem. A jsdom snapshot captures the serialized HTML, and it does not capture what the user sees. A browser-mode snapshot captures the rendered state, and the visual regression tools can compare screenshots. The trade-off is that a screenshot snapshot is more brittle across platforms and font rendering, so the text snapshots remain the default and the screenshots are an opt-in.
The trade-off. Browser mode is slower. Launching a browser takes seconds, and each test file that runs in browser mode pays that cost. The recommendation is to keep the pure logic and the simple rendering in jsdom, and to move to browser mode only the tests that need real layout, real events, or real focus. The projects configuration lets a single Vitest run hold both a jsdom project and a browser project, so the suite gets the best of both.
a. The provider configuration and the browser install
The browser mode is configured through the test.browser section of the Vitest config. The enabled flag turns it on, the provider names the browser automation library, and the instances array names the browsers to run against.
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
browser: {
enabled: true, // turn on browser mode
provider: "playwright", // the automation library
headless: true, // run without a visible window
instances: [
{ browser: "chromium" }, // the browser to run against
],
},
},
});
The provider is installed as a separate package, and the browser binaries are installed through the provider’s CLI. The playwright provider is the mature one, and the webdriverio provider is the alternative.
# install the provider package
npm install -D @vitest/browser-playwright playwright
# install the browser binaries
npx playwright install chromium
The instances array is the multi-browser declaration. Each entry names a browser, and Vitest runs the suite against every entry. The chromium, firefox, and webkit values map to the Playwright browsers.
// vitest.config.ts — three browsers in one run
export default defineConfig({
test: {
browser: {
enabled: true,
provider: "playwright",
instances: [
{ browser: "chromium" },
{ browser: "firefox" },
{ browser: "webkit" }, // Safari's engine
],
},
},
});
The headless: false option runs the browser with a visible window, which is the debugging mode. The --browser.headless=false CLI flag overrides the config for a single run.
b. The vitest-browser-react renderer and the locator API
The vitest-browser-react package exports a render function that mounts a React component into the browser document. The function returns a screen object with locators, and the locators are the query surface the test uses.
// Button.test.tsx
import { render } from "vitest-browser-react";
import { expect, test } from "vitest";
import { Button } from "./Button";
test("renders the button label", async () => {
// mount the component into the browser document
const screen = render(<Button>Save</Button>);
// locate the button by its accessible role
await expect.element(screen.getByRole("button")).toHaveTextContent("Save");
});
The render function is asynchronous in effect: the component mounts, and the locator assertions await until the element appears. The expect.element form is the browser-mode assertion, and it retries until the element matches or the timeout expires. This retry is what makes browser-mode tests resilient to the asynchronous rendering of React.
The locator methods mirror the testing-library queries, and they are the migration path. The getByRole is the preferred query because it matches the accessible tree, which is what a screen reader and a real user rely on.
// the locator queries
screen.getByRole("button", { name: "Save" }); // by accessible role and name
screen.getByText("Save"); // by visible text
screen.getByLabelText("Email"); // by form label
screen.getByPlaceholder("..."); // by placeholder
screen.getByTestId("submit-btn"); // by data-testid
The screen object also carries the container and the baseElement, so a test that needs the raw DOM can reach it. The locators are the recommended surface, and the raw DOM access is the escape hatch.
const screen = render(<Button>Save</Button>);
// the container is the mounted wrapper
const wrapper = screen.container;
// the baseElement is the document body
const body = screen.baseElement;
The render function accepts a wrapper option for a provider component, which is how a test supplies a context provider or a theme provider around the component under test.
import { render } from "vitest-browser-react";
import { ThemeProvider } from "./ThemeProvider";
const screen = render(<Button>Save</Button>, {
// wrap the component in the provider the app normally supplies
wrapper: ({ children }) => <ThemeProvider>{children}</ThemeProvider>,
});
c. The user-event API and the interaction pattern
The interaction API is userEvent, and it drives the browser’s real input pipeline. The click, type, keyboard, hover, and selectOptions methods generate the same events a real user would, including the focus and blur ordering and the pointer events.
import { render } from "vitest-browser-react";
import { userEvent } from "@vitest/browser/context";
import { expect, test } from "vitest";
import { Counter } from "./Counter";
test("increments the counter on click", async () => {
const screen = render(<Counter />);
// the real browser click, with focus and pointer events
await userEvent.click(screen.getByRole("button", { name: "Increment" }));
// the assertion retries until the text updates
await expect.element(screen.getByRole("status")).toHaveTextContent("1");
});
The userEvent.type method types into an input, and it generates the keydown, keypress, input, and keyup events in order. The clear option empties the field first, and the delay option spaces the keystrokes.
test("types into the search field", async () => {
const screen = render(< />);
const input = screen.getByRole("box");
// type with the real keyboard pipeline
await userEvent.type(input, "vitest", { delay: 10 });
// the input reflects the typed text
await expect.element(input).toHaveValue("vitest");
});
The userEvent.keyboard method sends a raw key sequence, which is how a test exercises shortcuts and form submission. The {Enter} token is a special key, and the plain characters are typed.
test("submits the form on Enter", async () => {
const screen = render(<Form on={on} />);
await userEvent.type(screen.getByRole("box"), "react");
await userEvent.keyboard("{Enter}"); // trigger the form submission
// the callback received the query
expect(on).toHaveBeenCalledWith("react");
});
The migration from testing-library is mechanical. The render import moves to vitest-browser-react, the fireEvent calls move to userEvent, and the screen.getBy* calls stay the same but are awaited through expect.element. The toBeInTheDocument matcher becomes toBeVisible, and the toHaveTextContent and toHaveValue matchers carry over.
// BEFORE — testing-library with jsdom
import { render, screen, fireEvent } from "@testing-library/react";
render(<Button>Save</Button>);
fireEvent.click(screen.getByRole("button"));
// AFTER — vitest-browser-react with browser mode
import { render } from "vitest-browser-react";
import { userEvent } from "@vitest/browser/context";
const screen = render(<Button>Save</Button>);
await userEvent.click(screen.getByRole("button"));
The expect.element assertion is the browser-mode-specific piece. The plain expect works on a locator’s resolved element, but expect.element is the retrying form that waits for the element to appear and match, which is what the asynchronous React render needs.
Complete Example Session
// ============================================
// PART 1: THE CONFIG
// ============================================
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
browser: {
enabled: true,
provider: "playwright",
headless: true,
instances: [{ browser: "chromium" }],
},
},
});
// ============================================
// PART 2: THE COMPONENT UNDER TEST
// ============================================
// Counter.tsx
import { useState } from "react";
export function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
<output aria-live="polite">{count}</output>
</div>
);
}
// ============================================
// PART 3: THE BASIC RENDER TEST
// ============================================
// Counter.test.tsx
import { render } from "vitest-browser-react";
import { expect, test } from "vitest";
import { Counter } from "./Counter";
test("renders the initial count", async () => {
const screen = render(<Counter />);
await expect.element(screen.getByRole("button")).toHaveTextContent("Increment");
await expect.element(screen.getByRole("status")).toHaveTextContent("0");
});
// ============================================
// PART 4: THE USER-EVENT INTERACTION
// ============================================
import { userEvent } from "@vitest/browser/context";
test("increments on click", async () => {
const screen = render(<Counter />);
await userEvent.click(screen.getByRole("button", { name: "Increment" }));
await expect.element(screen.getByRole("status")).toHaveTextContent("1");
});
// ============================================
// PART 5: THE PROVIDER WRAPPER
// ============================================
// Counter.test.tsx — with a theme provider
const screen = render(<Counter />, {
wrapper: ({ children }) => <ThemeProvider>{children}</ThemeProvider>,
});
// ============================================
// PART 6: THE FORM TYPING TEST
// ============================================
// Search.test.tsx
import { Search } from "./";
test("types into the search field", async () => {
const screen = render(< />);
const input = screen.getByRole("box");
await userEvent.type(input, "vitest", { delay: 10 });
await expect.element(input).toHaveValue("vitest");
});
// ============================================
// PART 7: THE KEYBOARD SHORTCUT TEST
// ============================================
test("submits on Enter", async () => {
const on = vi.fn();
const screen = render(<Form on={on} />);
await userEvent.type(screen.getByRole("box"), "react");
await userEvent.keyboard("{Enter}");
expect(on).toHaveBeenCalledWith("react");
});
// ============================================
// PART 8: THE MULTI-BROWSER INSTANCES
// ============================================
// vitest.config.ts — run against three engines
export default defineConfig({
test: {
browser: {
enabled: true,
provider: "playwright",
instances: [
{ browser: "chromium" },
{ browser: "firefox" },
{ browser: "webkit" },
],
},
},
});
// ============================================
// PART 9: THE HEADED DEBUG MODE
// ============================================
// run with a visible browser and pause at a point
// npx vitest --browser.headless=false
import { page } from "@vitest/browser/context";
test("debug with a visible browser", async () => {
const screen = render(<Counter />);
await page.pause(); // the browser stops here for inspection
});
// ============================================
// PART 10: THE MIGRATION FROM TESTING-LIBRARY
// ============================================
// BEFORE
import { render, screen, fireEvent } from "@testing-library/react";
render(<Button>Save</Button>);
fireEvent.click(screen.getByRole("button"));
// AFTER
import { render } from "vitest-browser-react";
import { userEvent } from "@vitest/browser/context";
const screen = render(<Button>Save</Button>);
await userEvent.click(screen.getByRole("button"));
The ten parts covered the config, the component, the render test, the user-event interaction, the provider wrapper, the form typing, the keyboard shortcut, the multi-browser instances, the headed debug mode, and the migration from testing-library.
Quick Reference
Browser Mode Config
| Option | Value | Effect |
|---|---|---|
enabled | true | Turn on browser mode |
provider | "playwright" | The automation library |
headless | true / false | Visible or invisible browser |
instances | [{ browser: "chromium" }] | The browsers to run |
Renderer and Queries
| API | Purpose |
|---|---|
render(<Component />) | Mount into the browser |
screen.getByRole | Query by accessible role |
screen.getByText | Query by visible text |
screen.getByLabelText | Query by form label |
screen.getByTestId | Query by data-testid |
Interaction and Assertions
| API | Purpose |
|---|---|
userEvent.click | Real browser click |
userEvent.type | Type with the key pipeline |
userEvent.keyboard | Send a raw key sequence |
expect.element | Retrying locator assertion |
toHaveTextContent | Assert the text |
toHaveValue | Assert the input value |
Best Practices
✅ Do This:
// prefer accessible role queries
screen.getByRole("button", { name: "Save" }); // ✅
// use userEvent instead of fireEvent
await userEvent.click(button); // ✅
// use the retrying assertion form
await expect.element(screen.getByRole("status")).toHaveTextContent("1"); // ✅
// supply the provider wrapper
render(<Counter />, { wrapper: ThemeProvider }); // ✅
// run headless in CI, headed locally
headless: process.env.CI === "true" // ✅
// keep simple rendering in jsdom
// browser mode only for real layout/events // ✅
❌ Don’t Do This:
// use testid when a role exists
screen.getByTestId("submit-btn"); // ❌
// dispatch synthetic events
fireEvent.click(button); // ❌
// assert without retrying
expect(screen.getByRole("status").element.textContent).toBe("1"); // ❌
// forget the provider the app needs
render(<Counter />); // crashes without ThemeProvider // ❌
// run headed in CI
headless: false; // ❌
// move every test to browser mode
// jsdom is faster for pure rendering // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Browser binaries missing | playwright install not run | Run npx playwright install |
| Locator never resolves | Element not rendered | Use expect.element retry |
| Provider context missing | No wrapper option | Supply the wrapper |
| Slow suite | Every test in browser mode | Keep jsdom for pure tests |
| Synthetic event mismatch | fireEvent used | Use userEvent |
| Flaky click | Element covered by overlay | Use the locator, not raw DOM |
Real-World Examples
1. Config
browser: { enabled: true, provider: "playwright" }
2. Install
npx playwright install chromium
3. Basic render
const screen = render(<Button>Save</Button>);
4. Role query
screen.getByRole("button", { name: "Save" });
5. Click
await userEvent.click(screen.getByRole("button"));
6. Type
await userEvent.type(input, "vitest", { delay: 10 });
7. Keyboard
await userEvent.keyboard("{Enter}");
8. Provider wrapper
render(<Counter />, { wrapper: ThemeProvider });
9. Multi-browser
instances: [{ browser: "chromium" }, { browser: "firefox" }]
10. Debug pause
await page.pause();
Visual
The Browser Mode Stack
┌─────────────────────────────────────────────────────────┐
│ VITEST (Node process) │
│ │
│ test file ──► browser mode runner │
│ │ │
│ ▼ │
│ PLAYWRIGHT PROVIDER ──► launches the browser │
│ │ │
│ ▼ │
│ REAL BROWSER (Chromium) │
│ ┌───────────────────────────────────────┐ │
│ │ render(<Counter />) │ │
│ │ userEvent.click(...) │ │
│ │ expect.element(...) │ │
│ └───────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
The Render and Query Flow
┌─────────────────────────────────────────────────────────┐
│ render(<Counter />) │
│ │ │
│ ▼ │
│ screen.getByRole("button") │
│ │ │
│ ▼ │
│ userEvent.click(locator) │
│ │ │
│ ▼ │
│ expect.element(locator).toHaveTextContent("1") │
│ │ │
│ ▼ │
│ retries until the text matches or the timeout │
└─────────────────────────────────────────────────────────┘
jsdom Versus Browser Mode
┌─────────────────────────────────────────────────────────┐
│ jsdom BROWSER MODE │
│ ───── ──────────── │
│ no layout engine real layout │
│ no CSS cascade real CSS │
│ synthetic events real event pipeline │
│ fast, no browser launch slower, needs binaries │
│ good for pure rendering good for real UX │
└─────────────────────────────────────────────────────────┘
The Migration Path
┌─────────────────────────────────────────────────────────┐
│ BEFORE (testing-library + jsdom) │
│ render, screen, fireEvent │
│ │
│ AFTER (vitest-browser-react + browser mode) │
│ render ──► vitest-browser-react │
│ screen.getBy* ──► same, awaited via expect.element │
│ fireEvent ──► userEvent │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Browser mode | Real browser through Playwright |
| Config key | test.browser |
| Provider | playwright or webdriverio |
| Renderer | vitest-browser-react |
| Render API | render(<Component />) |
| Query API | screen.getByRole, getByText, getByLabelText |
| Interaction | userEvent.click, type, keyboard |
| Assertion | expect.element(...).toHaveTextContent |
| Debug | page.pause() in headed mode |
| Migration | fireEvent → userEvent |
Key takeaways:
- Browser mode runs tests in a real browser. The Playwright provider launches Chromium, Firefox, or WebKit, and the test exercises real layout, real CSS, and the real event pipeline, which jsdom cannot provide.
vitest-browser-reactrenders the component into that browser. Therenderfunction returns ascreenwith locators, and the locators are the query surface the test uses.- The locators replace the testing-library queries.
getByRole,getByText,getByLabelText, andgetByTestIdcarry over, andgetByRoleis the preferred one because it matches the accessible tree. userEventreplacesfireEvent. The user-event API drives the browser’s real input pipeline, including the focus and blur ordering and the pointer events, so the component sees the same events a real user generates.expect.elementis the retrying assertion. It waits for the element to appear and match, which is what the asynchronous React render needs, and it is the browser-mode-specific piece that makes the tests resilient.- Browser mode is heavier than jsdom. Keep the pure logic and the simple rendering in jsdom, and move to browser mode only the tests that need real layout, real events, or real focus. The
projectsconfig can hold both.
Remember: Browser mode exists because jsdom cannot see layout, cannot run CSS, and cannot drive the real event pipeline. The vitest-browser-react renderer mounts a React component into a real browser, the locators query the accessible tree, and userEvent drives the real input pipeline. The trade-off is weight: a browser launch is slower than a jsdom render, so the recommendation is to keep the simple tests in jsdom and to move only the tests that need the real browser to browser mode. The migration from testing-library is mechanical: the render import moves, fireEvent becomes userEvent, and the query calls stay the same but are awaited through expect.element.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!