Vitest for React: Component, Hook, and Integration Testing
Test React components, hooks, and user flows with Vitest and Testing Library: jsdom setup, mocking, snapshots, integration tests, and CI coverage.
Introduction
You’ve got a React component that works in the browser but you’re afraid to touch it — one rename and something breaks silently. A Vitest suite with React Testing Library fixes that: tests exercise the component the way a user does (render it, click it, read what is on screen), so a refactor that keeps the behavior keeps the suite green.
Vitest is a test runner built on the same transform pipeline as Vite, which means your TypeScript, JSX, and path aliases work in tests exactly as they do in the app, with no second toolchain to configure. It speaks the Jest API (describe, it, expect, vi.fn), so tests read familiar and porting an old suite is mostly mechanical. This guide sets up a real testing project: jsdom environment, component and hook tests, three levels of mocking, snapshots, an end-to-end user flow, and a CI job that enforces coverage. A runnable companion project contains every file shown here.
When to Use Vitest for React Testing
Vitest earns its place in most React codebases that already build with Vite:
- Vite + React projects: the test runner shares your
vite.config.tsplugins and resolve aliases, soimport { Button } from "@/components/Button"resolves identically in tests and in the app. - Component and hook unit tests: jsdom plus React Testing Library gives you a DOM, events, and accessibility-oriented queries without a browser process.
- Suites that run on every save: Vitest’s watch mode re-runs only affected files and reports in milliseconds, which makes test-driven workflows practical.
- Teams migrating off Jest: the API surface is nearly identical (
vireplacesjest), and most suites port by changing imports rather than rewriting assertions.
Cases where it’s the wrong tool:
- Non-Vite projects: a Create React App or a custom webpack setup gains little; Jest already understands that toolchain and adding Vitest means maintaining two configurations.
- End-to-end coverage: Vitest isn’t a browser driver. Real navigation, auth flows, and cross-page state belong to Playwright or Cypress.
- Mature Jest suites without pain: if the existing suite is fast enough and nobody is migrating the build to Vite, a runner swap buys speed but not new coverage.
Vitest vs Jest
Both runners share the same mental model (suites, mocks, assertions), but they differ where it matters daily:
| Aspect | Vitest | Jest |
|---|---|---|
| Transform | Vite pipeline (esbuild, native ESM) | babel-jest / ts-jest |
| Config | test block inside vite.config.ts | Separate jest.config.js + transform rules |
| ESM/TSX | Native, zero setup | Requires transform configuration |
| Watch speed | Instant HMR-based re-runs | Re-runs affected files, slower on large repos |
| API | describe/it/expect/vi, Jest-compatible | describe/it/expect/jest |
| Extra modes | Browser Mode (@vitest/browser), benchmarks, typecheck | jsdom + node, mature snapshot ecosystem |
The practical rule: on Vite projects pick Vitest and never look back; on webpack projects staying on Jest is a legitimate choice.
Setup
A working React test environment needs three pieces: the runner, a DOM implementation, and the Testing Library packages that render and query components.
Install the toolchain
npm install -D vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdom
@testing-library/jest-dom adds assertions like toBeInTheDocument(); @testing-library/user-event drives realistic interactions (focus, typing, clicks in sequence) instead of raw DOM events. If your project lives outside Vite, vitest.config.ts is standalone. The plugin only wires React’s JSX transform.
Configure vitest.config.ts
// vitest.config.ts: Vitest configuration for React
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import { resolve } from "path";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
globals: true,
setupFiles: ["./tests/setup.ts"],
css: true,
coverage: {
provider: "v8",
reporter: ["text", "json", "html"],
include: ["src/**/*.{ts,tsx}"],
exclude: ["src/**/*.d.ts", "src/main.tsx"],
thresholds: {
lines: 80,
functions: 80,
branches: 75,
statements: 80,
},
},
},
resolve: {
alias: {
"@": resolve(__dirname, "./src"),
},
},
});
Three decisions here deserve a comment. environment: "jsdom" gives tests a DOM without a browser — faster than a real browser and accurate enough for component logic; happy-dom is a lighter alternative if startup time matters, at the cost of some layout APIs. globals: true makes describe/it/expect/vi available without imports; this guide still imports them explicitly in examples because it makes each file self-contained and easier to copy into projects that disable globals. The thresholds block turns coverage into a contract: CI fails when lines or branches drop below the floor, which prevents silent coverage erosion.
The setup file
// tests/setup.ts: Global test setup
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach, vi } from "vitest";
// Clean up DOM after each test
afterEach(() => {
cleanup();
});
// Mock matchMedia (not available in jsdom)
Object.defineProperty(window, "matchMedia", {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
// Mock IntersectionObserver
class MockIntersectionObserver {
observe = vi.fn();
unobserve = vi.fn();
disconnect = vi.fn();
takeRecords = vi.fn();
}
Object.defineProperty(window, "IntersectionObserver", {
writable: true,
configurable: true,
value: MockIntersectionObserver,
});
jsdom ships a useful subset of browser APIs, not all of them. matchMedia and IntersectionObserver are the two that most commonly crash React tests — components that render responsive variants or lazy-load content call them on mount. Stubbing them once in the setup file beats discovering the gap inside a failing test. cleanup() unmounts every rendered tree between tests, which prevents one test’s DOM from leaking assertions into the next.
Writing Component Tests
A component test renders the component, interacts with it like a user, and asserts on what a user would perceive. Here is a small but complete example:
// tests/components/Button.test.tsx: Basic component test
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Button } from "@/components/Button";
describe("Button", () => {
it("renders with correct text", () => {
render(<Button>Click me</Button>);
expect(screen.getByRole("button", { name: /click me/i })).toBeInTheDocument();
});
it("calls onClick when clicked", async () => {
const user = userEvent.setup();
const handleClick = vi.fn();
render(<Button onClick={handleClick}>Click me</Button>);
await user.click(screen.getByRole("button"));
expect(handleClick).toHaveBeenCalledOnce();
});
it("does not call onClick when disabled", async () => {
const user = userEvent.setup();
const handleClick = vi.fn();
render(<Button onClick={handleClick} disabled>Click me</Button>);
await user.click(screen.getByRole("button"));
expect(handleClick).not.toHaveBeenCalled();
});
it("applies variant classes", () => {
const { rerender } = render(<Button variant="primary">Primary</Button>);
expect(screen.getByRole("button")).toHaveClass("btn-primary");
rerender(<Button variant="danger">Danger</Button>);
expect(screen.getByRole("button")).toHaveClass("btn-danger");
});
});
The pattern that makes this suite resilient is visible in every assertion: queries go through screen and target roles, labels, and text — never CSS classes or internal state. The one exception is toHaveClass, and even there the test checks a public styling contract (variants), not an implementation detail. userEvent.setup() returns a session that reproduces real input behavior (hovering, focusing, and firing the full event sequence a browser would), which is why it catches interaction bugs that fireEvent’s single synthetic events miss.
Query the DOM the way users do
Testing Library exposes a family of getBy* queries, and the order in which you reach for them encodes how closely your test tracks real accessibility:
| Priority | Query | Finds | Reach for it when |
|---|---|---|---|
| 1 | getByRole | Elements by ARIA role + accessible name | Almost always — buttons, headings, inputs, dialogs |
| 2 | getByLabelText | Form fields by their <label> | Inputs, selects, textareas |
| 3 | getByPlaceholderText | Inputs without a real label | Legacy forms that lack labels (add one anyway) |
| 4 | getByText | Elements by visible text | Non-interactive content: paragraphs, list items |
| 5 | getByTestId | data-testid hooks | Last resort — charts, third-party widgets, visual output |
When a getByRole query fails, the error message prints the accessibility tree of what was rendered — that tree is the fastest way to see both why your test failed and how a screen reader perceives the component. If getByRole can’t find your button, that usually means the button is missing an accessible name, which is a real usability bug the test just caught for free.
The getBy* family throws when nothing matches, which is what you want for asserting presence. For asserting absence, use queryBy* (expect(screen.queryByText(/error/i)).not.toBeInTheDocument()), because getByText would throw instead of returning null. And for content that arrives asynchronously, findBy* returns a promise that resolves when the element appears — equivalent to waitFor + getBy* in one call.
Testing forms and validation
Forms exercise three things at once: controlled inputs, validation state, and async submission. Test all three from the user’s perspective — type, submit, read the error or the result:
// tests/components/LoginForm.test.tsx: Form testing
import { describe, it, expect, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { LoginForm } from "@/components/LoginForm";
describe("LoginForm", () => {
it("submits with valid credentials", async () => {
const user = userEvent.setup();
const onSubmit = vi.fn();
render(<LoginForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText(/email/i), "user@example.com");
await user.type(screen.getByLabelText(/password/i), "password123");
await user.click(screen.getByRole("button", { name: /submit/i }));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({
email: "user@example.com",
password: "password123",
});
});
});
it("shows validation errors for empty fields", async () => {
const user = userEvent.setup();
const onSubmit = vi.fn();
render(<LoginForm onSubmit={onSubmit} />);
await user.click(screen.getByRole("button", { name: /submit/i }));
expect(screen.getByText(/email is required/i)).toBeInTheDocument();
expect(screen.getByText(/password is required/i)).toBeInTheDocument();
expect(onSubmit).not.toHaveBeenCalled();
});
it("validates email format", async () => {
const user = userEvent.setup();
render(<LoginForm onSubmit={vi.fn()} />);
await user.type(screen.getByLabelText(/email/i), "not-an-email");
await user.type(screen.getByLabelText(/password/i), "password123");
await user.click(screen.getByRole("button", { name: /submit/i }));
expect(screen.getByText(/invalid email format/i)).toBeInTheDocument();
});
});
Note the waitFor around the submit assertion. Validation and submission handlers often resolve on the next tick or after a microtask, so asserting synchronously would be timing-dependent — the classic source of flaky tests. waitFor retries the assertion until it passes or times out (default: one second), which makes the test deterministic without sprinkling setTimeout guesses.
Testing async components
Components that fetch data move through loading → success/error states, and each state is worth a test. Mock the data layer at the module boundary so the test controls the outcome:
// tests/components/UserProfile.test.tsx: Async component testing
import { describe, it, expect, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import { UserProfile } from "@/components/UserProfile";
vi.mock("@/api/users", () => ({
fetchUser: vi.fn(),
}));
import { fetchUser } from "@/api/users";
describe("UserProfile", () => {
it("shows loading state then user data", async () => {
vi.mocked(fetchUser).mockResolvedValue({
id: 1,
name: "Alice",
email: "alice@example.com",
});
render(<UserProfile userId={1} />);
// Loading state
expect(screen.getByText(/loading/i)).toBeInTheDocument();
// Data loaded
await waitFor(() => {
expect(screen.getByText("Alice")).toBeInTheDocument();
expect(screen.getByText("alice@example.com")).toBeInTheDocument();
});
});
it("shows error message on fetch failure", async () => {
vi.mocked(fetchUser).mockRejectedValue(new Error("Network error"));
render(<UserProfile userId={1} />);
await waitFor(() => {
expect(screen.getByText(/network error/i)).toBeInTheDocument();
});
});
});
vi.mock is hoisted to the top of the file by Vitest’s transform, which is why import { fetchUser } below it receives the mock rather than the real module. vi.mocked(fetchUser) wraps the import with its mock type so mockResolvedValue type-checks. Two details matter for flakiness: asserting the loading state before awaiting keeps the test honest about the intermediate render, and each test resets the mock’s behavior: add vi.clearAllMocks() in a beforeEach when suites grow, or one test’s mockResolvedValue will leak into the next.
Testing Custom Hooks
renderHook mounts a hook inside a test component and exposes its return value through result.current. State updates still need act(), the wrapper that flushes effects, which comes from @testing-library/react, not from vitest:
// tests/hooks/useCounter.test.ts: Hook testing
import { describe, it, expect } from "vitest";
import { renderHook, act } from "@testing-library/react";
import { useCounter } from "@/hooks/useCounter";
describe("useCounter", () => {
it("initializes with default value", () => {
const { result } = renderHook(() => useCounter());
expect(result.current.count).toBe(0);
});
it("initializes with custom value", () => {
const { result } = renderHook(() => useCounter(10));
expect(result.current.count).toBe(10);
});
it("increments count", () => {
const { result } = renderHook(() => useCounter());
act(() => result.current.increment());
expect(result.current.count).toBe(1);
act(() => result.current.increment());
expect(result.current.count).toBe(2);
});
it("decrements count", () => {
const { result } = renderHook(() => useCounter(5));
act(() => result.current.decrement());
expect(result.current.count).toBe(4);
});
it("resets count", () => {
const { result } = renderHook(() => useCounter(10));
act(() => result.current.increment());
expect(result.current.count).toBe(11);
act(() => result.current.reset());
expect(result.current.count).toBe(10);
});
});
The renderHook call also accepts an options object: initialProps feeds props into the hook and rerender exercises it with new values, and wrapper mounts the hook inside providers (useful for hooks that consume context or React Query). Rules of hooks still apply — the callback must invoke the hook unconditionally.
Hooks that wait (debounce, polling, delayed effects) pair renderHook with fake timers so tests control time instead of sleeping:
// tests/hooks/useDebounce.test.ts: Debounce hook testing
import { describe, it, expect, vi } from "vitest";
import { renderHook, act } from "@testing-library/react";
import { useDebounce } from "@/hooks/useDebounce";
describe("useDebounce", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("returns initial value immediately", () => {
const { result } = renderHook(() => useDebounce("hello", 500));
expect(result.current).toBe("hello");
});
it("updates value after delay", () => {
const { result, rerender } = renderHook(
({ value, delay }) => useDebounce(value, delay),
{ initialProps: { value: "hello", delay: 500 } }
);
rerender({ value: "world", delay: 500 });
expect(result.current).toBe("hello"); // Still old value
act(() => {
vi.advanceTimersByTime(500);
});
expect(result.current).toBe("world"); // Now updated
});
});
vi.useFakeTimers() replaces setTimeout, setInterval, and Date.now with mocks you drive manually via advanceTimersByTime, runAllTimers, or setSystemTime. The afterEach restore isn’t optional hygiene — fake timers left running will freeze every async test that follows them in the same worker. For code that uses dates rather than delays, vi.setSystemTime(new Date("2026-01-15")) freezes the clock without touching timers at all.
Mocking
Every test needs a boundary where real behavior stops and controlled behavior starts. Pick the boundary at module edges (API clients, SDK wrappers, third-party services) and mock there, not inside the component. The test double pattern explains the vocabulary behind these choices: mocks, stubs, spies, and fakes each replace a different kind of dependency.
Module mocks
// tests/mocks/api.test.ts: Module mocking
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/api/client", () => ({
apiClient: {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn(),
},
}));
import { apiClient } from "@/api/client";
import { UserService } from "@/services/UserService";
describe("UserService", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("fetches users", async () => {
vi.mocked(apiClient.get).mockResolvedValue({
data: [{ id: 1, name: "Alice" }],
});
const users = await UserService.getAll();
expect(users).toHaveLength(1);
expect(apiClient.get).toHaveBeenCalledWith("/users");
});
it("creates user", async () => {
vi.mocked(apiClient.post).mockResolvedValue({
data: { id: 2, name: "Bob" },
});
const user = await UserService.create({ name: "Bob" });
expect(user.id).toBe(2);
expect(apiClient.post).toHaveBeenCalledWith("/users", { name: "Bob" });
});
});
The factory function passed to vi.mock defines the entire module surface — anything not returned becomes undefined, which is a frequent source of “X is not a function” failures when the real module exports more than you remembered. Keep the fake surface minimal but complete for what the code under test touches.
Mocking context providers
Components that consume context don’t need their context mocked: they need a real provider with controlled values. A small render helper keeps tests declarative:
// tests/components/ThemeAwareComponent.test.tsx: Context mocking
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { ThemeContext, Theme } from "@/contexts/ThemeContext";
import { ThemeAwareComponent } from "@/components/ThemeAwareComponent";
function renderWithTheme(ui: React.ReactNode, theme: Theme = "light") {
return render(
<ThemeContext.Provider value={{ theme, toggleTheme: vi.fn() }}>
{ui}
</ThemeContext.Provider>
);
}
describe("ThemeAwareComponent", () => {
it("renders light theme styles", () => {
renderWithTheme(<ThemeAwareComponent />, "light");
expect(screen.getByTestId("themed")).toHaveClass("light");
});
it("renders dark theme styles", () => {
renderWithTheme(<ThemeAwareComponent />, "dark");
expect(screen.getByTestId("themed")).toHaveClass("dark");
});
});
A vi.fn() stands in for toggleTheme so the test can also assert the component calls it when the user toggles. For deeper trees (router, query client, auth), accumulate providers in a wrapper option instead of nesting renders: renderHook(() => useCart(), { wrapper: AllProviders }).
Partial mocks
Sometimes only one export needs controlling while the rest of the module should stay real — a classic case is freezing formatDate while keeping formatCurrency intact:
// tests/mocks/partial.test.ts: Partial module mocking
import { describe, it, expect, vi } from "vitest";
vi.mock("@/utils/format", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/utils/format")>();
return {
...actual,
formatDate: vi.fn(() => "2026-01-01"),
};
});
import { formatDate, formatCurrency } from "@/utils/format";
describe("partial mock", () => {
it("uses mocked formatDate", () => {
expect(formatDate(new Date())).toBe("2026-01-01");
});
it("uses real formatCurrency", () => {
expect(formatCurrency(10.5)).toBe("$10.50");
});
});
importOriginal loads the real module so the factory can spread it and override selectively. Reach for this when a module mixes pure functions you want to keep with impure ones you need to freeze: date/time utilities, ID generators, random helpers. If you find yourself partially mocking most of a module’s exports, the boundary is wrong: the impure part probably belongs in its own module.
Mocking HTTP with MSW
vi.mock answers “what did my code call”; Mock Service Worker answers “what does the network see”. MSW 2.x intercepts real fetch/XMLHttpRequest calls at the network layer via setupServer, so components exercise their real request code (URL construction, headers, error handling) against responses you declare:
// src/mocks/server.ts: MSW server for tests
import { setupServer } from "msw/node";
import { http, HttpResponse } from "msw";
export const server = setupServer(
http.get("/api/users/:id", ({ params }) => {
return HttpResponse.json({
id: Number(params.id),
name: "Alice",
email: "alice@example.com",
});
})
);
// tests/components/UserProfileMsw.test.tsx: Testing with MSW
import { describe, it, expect, beforeAll, afterEach, afterAll } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import { http, HttpResponse } from "msw";
import { server } from "@/mocks/server";
import { UserProfile } from "@/components/UserProfile";
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
describe("UserProfile with MSW", () => {
it("renders user data from the intercepted request", async () => {
render(<UserProfile userId={1} />);
await waitFor(() => {
expect(screen.getByText("Alice")).toBeInTheDocument();
});
});
it("shows the error state on a 500", async () => {
server.use(
http.get("/api/users/:id", () => {
return new HttpResponse(null, { status: 500 });
})
);
render(<UserProfile userId={1} />);
await waitFor(() => {
expect(screen.getByText(/failed to load/i)).toBeInTheDocument();
});
});
});
The trade-off against vi.mock: MSW tests cover more real code (the fetch wrapper itself runs) and handlers can be shared across the suite and even between test and dev environments, at the price of one more dependency and slightly more setup. The practical split used by most teams — vi.mock for SDKs and thin wrappers, MSW for anything that goes through fetch.
Snapshot Testing
Snapshots serialize rendered output and diff it against a stored baseline. They shine on stable, presentational components where any DOM change is worth a human glance, not on logic, where assertions already say more:
// tests/components/Card.snapshot.test.tsx: Snapshot testing
import { describe, it, expect } from "vitest";
import { render } from "@testing-library/react";
import { Card } from "@/components/Card";
describe("Card snapshots", () => {
it("matches snapshot with content", () => {
const { container } = render(
<Card title="Test Title" description="Test Description" />
);
expect(container.firstChild).toMatchSnapshot();
});
it("matches snapshot with image", () => {
const { container } = render(
<Card title="With Image" image="/test.jpg" />
);
expect(container.firstChild).toMatchSnapshot();
});
it("matches inline snapshot", () => {
const { container } = render(<Card title="Inline" />);
expect(container.firstChild).toMatchInlineSnapshot(`
<div
class="card"
>
<h3>
Inline
</h3>
</div>
`);
});
});
toMatchSnapshot writes __snapshots__/*.snap files that go into version control — review them in diffs, because a snapshot approved carelessly is a bug you froze in place. toMatchInlineSnapshot keeps the expected markup inside the test, which makes small components self-documenting but bloats the file for anything non-trivial. The deeper guide on Vitest Snapshot Testing for React covers snapshot updates (vitest -u), serializer options, and when to drop snapshots entirely for explicit assertions.
Integration Testing
Unit tests verify pieces; integration tests verify the seams between them — component ↔ service ↔ store. The Checkout flow below crosses a form, an API mock, and multi-step UI state in one test:
// tests/integration/checkout.test.tsx: Integration test
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { CheckoutFlow } from "@/pages/CheckoutFlow";
vi.mock("@/api/orders", () => ({
createOrder: vi.fn(),
calculateShipping: vi.fn(),
}));
import { createOrder, calculateShipping } from "@/api/orders";
describe("Checkout flow integration", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(calculateShipping).mockResolvedValue({ cost: 5.99 });
vi.mocked(createOrder).mockResolvedValue({ id: "order-123", status: "confirmed" });
});
it("completes full checkout flow", async () => {
const user = userEvent.setup();
render(<CheckoutFlow items={[{ id: 1, name: "Widget", price: 10, qty: 2 }]} />);
// Step 1: Review cart
expect(screen.getByText("Widget")).toBeInTheDocument();
expect(screen.getByText("$20.00")).toBeInTheDocument();
// Step 2: Enter shipping
await user.click(screen.getByRole("button", { name: /continue to shipping/i }));
await user.type(screen.getByLabelText(/address/i), "123 Main St");
await user.type(screen.getByLabelText(/city/i), "New York");
await user.type(screen.getByLabelText(/zip/i), "10001");
// Wait for shipping calculation
await waitFor(() => {
expect(screen.getByText("$5.99")).toBeInTheDocument();
});
// Step 3: Place order
await user.click(screen.getByRole("button", { name: /place order/i }));
await waitFor(() => {
expect(screen.getByText(/order confirmed/i)).toBeInTheDocument();
expect(screen.getByText("order-123")).toBeInTheDocument();
});
expect(createOrder).toHaveBeenCalledWith(
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({ id: 1, qty: 2 }),
]),
shipping: expect.objectContaining({
address: "123 Main St",
city: "New York",
zip: "10001",
}),
})
);
});
});
Integration tests are expensive (slow to write, slow to run, first to break on a redesign), so they earn their keep only on the paths where a bug costs real money or users. The test pyramid keeps the proportions honest:
Most suites should look like the left side: broad unit coverage, a layer of component tests on interactive UI, a thin set of integration tests on the few flows that must work end to end, and a handful of browser tests. The testing strategy guide sizes each layer against team and codebase scale.
Vitest Browser Mode
Everything so far runs in jsdom — a JavaScript DOM simulation that’s fast but not a browser. Since Vitest 2, @vitest/browser runs component tests in a real browser (Playwright, WebdriverIO, or WebKit preview) while keeping the same runner and assertions:
// vitest.config.ts: Browser mode for component testing
export default defineConfig({
plugins: [react()],
test: {
browser: {
enabled: true,
provider: "playwright",
instances: [{ browser: "chromium" }],
headless: true,
},
},
});
Real layout, real event semantics, real CSS — Browser Mode catches the class of bugs jsdom structurally can’t: focus management, scroll behavior, CSS-dependent visibility, ResizeObserver. The cost is real as well: slower startup, a browser to install in CI, and an API surface that’s still settling (it reached stability with Vitest 3). The pragmatic answer for most teams isn’t either/or — keep the bulk of the suite in jsdom where speed dominates, and run Browser Mode on the subset of components whose behavior depends on layout or focus.
Running Tests in CI
In CI you want one non-interactive run with coverage, not a watch session:
# .github/workflows/test.yml: Vitest in CI
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npx vitest run --coverage
- name: Upload coverage
uses: codecov/codecov-action@v4
with:
file: ./coverage/coverage-final.json
vitest run executes once and exits non-zero on failure; the v8 coverage reporter writes coverage-final.json for the upload step and enforces the thresholds from vitest.config.ts, so a coverage drop fails the build even when every test passes. The scripts that complete the picture:
{
"scripts": {
"test": "vitest",
"test:run": "vitest run",
"test:ui": "vitest --ui",
"test:coverage": "vitest run --coverage",
"test:watch": "vitest watch"
}
}
vitest --ui opens the browser-based UI during development (file filtering, watch controls, inline failure diffs), which is worth the extra @vitest/ui install on larger suites.
Best Practices
- Test behavior, not implementation: query by role, label, or text; when a refactor keeps the UI identical the suite should stay green. Tests that poke at state or CSS selectors break on every cleanup and teach the team to ignore failures.
- Prefer
userEventoverfireEvent:userEventreproduces the event sequence a real user triggers (hover, focus, keydown, click), whilefireEventdispatches a single synthetic event that skips half the interaction contract. - Mock at the module boundary: mock API clients, SDK wrappers, and the network layer, never functions inside the component under test. Internal mocks make the test verify the mock rather than the code.
- Use
screenqueries: destructuringgetByTextfromrender()captures stale references that break on re-render;screenalways queries the current DOM. - Let queries enforce accessibility: reaching for
getByRolefirst surfaces missing accessible names as test failures, which is free a11y auditing. - Keep tests independent: no shared mutable state, no ordering assumptions;
cleanup()after each render andvi.clearAllMocks()where mocks accumulate. - Await async assertions:
waitFor,findBy*, orawait user.*calls; synchronous assertions on async updates are the top cause of flaky suites. - Treat coverage as a floor, not a target: enforce thresholds in CI to stop regression, but a line hit by a useless test counts the same as one hit by a real one.
Common Mistakes
- Testing implementation details: asserting on component state or internal functions instead of rendered output. The suite then fails on every safe refactor — exactly backwards from what tests should protect.
fireEventwhereuserEventbelongs:fireEvent.changefires one event and skips the focus/typing sequence validation libraries often depend on, so the test passes while the real interaction fails.- Assertions without awaiting: the test finishes while the fetch promise is still pending, the assertion runs against the loading state, and the suite reports green on broken code.
waitForexists for this. - Over-mocking: mocking the component’s own module, its utils, and its context ends up testing whether mocks return what mocks were told to return. Boundaries, not internals.
- Snapshots on dynamic content: components with dates, random IDs, or animations produce a diff on every run, and teams learn to blindly approve
-uupdates — at which point the snapshot is noise. - Fake timers leaking:
vi.useFakeTimers()withoutvi.useRealTimers()inafterEachfreezes the clock for every subsequent test in the file, producing timeouts that look unrelated to their cause.
See Also
- Vitest documentation — component testing and browser mode: the canonical reference for config options, coverage, and
@vitest/browser. - React Testing Library docs: queries,
userEvent, and the testing philosophy behind the API. - Testing Library query priority: the official ordering this guide condenses.
- MSW documentation: network-level mocking shared between tests and development.
- Vitest vs Jest migration notes: API differences worth knowing before porting a suite.
Frequently Asked Questions
What is Vitest?
A Vite-native test runner with Jest-compatible APIs. Tests run through the same transform pipeline as the app, so TypeScript, JSX, and ESM work without a second configuration layer.
How is Vitest different from Jest?
Vitest reuses your Vite config — plugins, aliases, transforms — where Jest keeps its own (jest.config.js, babel-jest, ts-jest). For Vite projects that removes an entire parallel toolchain; for non-Vite projects Jest remains the native fit.
Should I test components or hooks first?
Test what ships. A hook's logic is already covered when the component using it gets tested through the UI. Reserve renderHook for hooks with their own contracts: shared utilities, hooks consumed by several components, or complex state machines.
How do I mock API calls in Vitest?
vi.mock("@/api/client", () => ({ ... })) replaces the whole module; importOriginal inside the factory keeps the exports you don't override. If the code uses fetch directly, intercept the network with MSW instead of mocking the caller.
When should I prefer Browser Mode over jsdom?
When the component's correctness depends on real browser behavior — focus traps, scroll position, CSS visibility, ResizeObserver, or visual clipping. jsdom covers component logic faster; Browser Mode covers the rendering truth.
How do I test code that uses timers or dates?
vi.useFakeTimers() takes over setTimeout, setInterval, and the clock; drive it with advanceTimersByTime and restore with vi.useRealTimers() in afterEach. vi.setSystemTime freezes Date.now alone when only timestamps matter.
Do snapshots replace assertions?
No. Snapshots detect change, not correctness — they tell you the markup moved, not whether it moved rightly. Keep them for stable presentational components and assert behavior explicitly everywhere else.
Related Resources
Test-Driven Development (TDD) — A Practical Workflow
Learn TDD step by step: write a failing test, make it pass, refactor. Red-Green-Refactor with real examples in Python, JavaScript, and Java.
GuideSoftware Testing Strategy Guide
A practical guide to building a layered testing strategy with unit, integration, contract, and end-to-end tests that your team will actually maintain.
GuideComplete Guide to React Performance Optimization
Optimize React apps for speed. Covers memoization, virtualization, code splitting, bundle analysis, React Profiler, concurrent features, and Core Web Vitals.
PatternTest Double: Replace Dependencies with Stubs, Spies, Fakes
How to use test doubles to isolate units under test. Covers stubs, spies, fakes, mocks, and dummy objects with examples in Python, JavaScript, and Java.
RecipeVitest Snapshot Testing for React
How to use Vitest snapshot testing to catch unintended UI changes in React components, including inline snapshots and snapshot update workflows.
RecipeSnapshot Testing React Components with Jest
How to use Jest snapshot testing to catch unintended UI regressions in React components and prevent visual bugs from reaching production