Editorâs Note: This post comparing React testing libraries post was last updated on 3 December 2026 by Jude Miracle to clarify the roles of React testing tools, update the Jest examples, and add guidance on Vitest Browser Mode and Playwright.
React testing tools handle different parts of a test suite. Jest and Vitest run tests, React Testing Library helps you render and query components, and tools such as Cypress and Playwright exercise your app in a browser.
For a Vite-based React app, Vitest with React Testing Library is a practical starting point for component tests. Existing Jest suites can continue using React Testing Library, with browser tests added where the application needs them.
Testing helps you assess your projectâs stability and catch regressions before you roll out changes. Letâs look at the testing strategies and tools you can use, with examples for each.
The authorâs StackBlitz demo contains the Vite, Vitest, and React Testing Library samples. Run the browser examples locally with the required browser binaries installed.
For the dependency versions used here, use Node.js v24.15 or later in the v24 release line. The examples use Jest v30 and Vitest v5; the Jest configuration pins Babel to v7 for compatibility with babel-jest.
There are several ways to test React applications, from individual functions to complete user flows. Before we dive into the frameworks and libraries, letâs examine the scope of each approach.
A unit test checks a small piece of code in isolation. For example, you can test whether a validation function returns the expected result for a given input. These tests generally require little setup and are inexpensive to run.
An integration test checks how multiple parts of an application work together. For example, you can render a registration form with its validation logic and check how it responds to an API result.
You can mock the network boundary or use a test backend, depending on what you want to verify. Integration tests usually require more setup than isolated unit tests.
End-to-end tests exercise complete workflows through a running application, such as signing in and placing an order. Use controlled test accounts and data to check how the frontend and backend work together.
When writing component tests, focus on behavior users can observe. Assertions about private state or component structure can break during a refactor even when the interface still works correctly.
With those testing scopes in mind, letâs take a closer look at the tools and how they fit together.
Testing tools cover several roles, and youâll often combine them:
| Role | What it does | Tools | Used with |
|---|---|---|---|
| Test runner | Discovers and executes tests; provides assertions and mocking APIs | Vitest, Jest | A renderer for component tests |
| Renderer and queries | Mounts components and locates elements through the DOM | React Testing Library, vitest-browser-react | A test runner and DOM environment |
| Browser component testing | Exercises individual components in a real browser | Vitest Browser Mode, Cypress component testing | Vitest or Cypressâs runner |
| End-to-end testing | Exercises workflows through a running app | Playwright Test, Cypress | The application and any required backend services |
React Testing Library supplies rendering and query utilities. Vitest or Jest executes the test file and provides assertions such as expect, so pairing a runner with React Testing Library gives you the pieces needed for the component examples below.
The choice of runner is separate from the choice of DOM environment. You can use jsdom for simulated DOM tests or run components in a browser, then add end-to-end coverage for important workflows.
Jest is a testing framework originally created at Facebook. It supports established React test suites and is included in the default React Native template. For a new Vite project, Vitest can reuse your Vite configuration and offers a Jest-compatible API, with some differences in mocking and configuration.
With Jest, you can:
Letâs get started with a JavaScript and JSX example. In a project that already has React and React DOM installed, add Jest, Babel, and React Testing Library:
npm install -D jest jest-environment-jsdom babel-jest @babel/core@7 @babel/preset-env@7 @babel/preset-react@7 @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom
Configure Babel to target your Node.js installation and transform JSX:
// babel.config.cjs in the root of your project
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
['@babel/preset-react', { runtime: 'automatic' }],
],
}
Next, tell Jest to use a simulated DOM environment and load the jest-dom matchers before each test file. Create these two files:
// jest.config.cjs
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
}
// jest.setup.js
import '@testing-library/jest-dom'
Add a test script to your existing package.json:
{
"scripts": {
"test": "jest"
}
}
Running npm test now starts Jest. This Babel configuration covers JavaScript and JSX; TypeScript projects need an appropriate TypeScript transform as well.
Jestâs default file patterns include names such as MyComponent.test.jsx and MyComponent.spec.js, as well as supported files in a __tests__ directory. Hereâs a small component to test:
// MyComponent.jsx
export const MyComponent = ({ label }) => {
return <div>{label}</div>;
};
The next step is to check that it displays the supplied label:
// MyComponent.test.jsx
import { render, screen } from '@testing-library/react'
import { MyComponent } from './MyComponent'
describe('MyComponent', () => {
test('should display label', () => {
render(<MyComponent label='Test' />)
expect(screen.getByText('Test')).toBeInTheDocument()
})
})
With this Jest setup, React Testing Library automatically unmounts rendered components after each test. You can use Jestâs lifecycle hooks for other setup and cleanup your tests require.
Jestâs beforeAll and afterAll hooks run once before and after the tests in their scope. At the top level, that scope is the test file; inside a describe block, it is the tests in that block.
Hereâs an example that creates and clears a shared fixture:
// shared-fixture.test.js
let customers;
beforeAll(() => {
customers = new Map([['customer-1', { name: 'Bob' }]]);
});
afterAll(() => {
customers.clear();
});
test('loads the shared customer fixture', () => {
expect(customers.get('customer-1')).toEqual({ name: 'Bob' });
});
For asynchronous setup or teardown, return a promise or use an async hook and await the operation. Jest waits for it to finish before continuing.
Use beforeEach and afterEach for work that must happen around every test. For example, if you create DOM elements directly, remove those elements after each test:
// dom-fixture.test.js
let container;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
container.remove();
});
test('can add content to the container', () => {
container.textContent = 'Hello';
expect(container).toHaveTextContent('Hello');
});
test('starts with an empty container', () => {
expect(container).toBeEmptyDOMElement();
});
React Testing Library handles cleanup for the components it renders. The manual removal above is for the element created directly by the test.
The describe function groups related tests in the output:
// MyComponent.grouped.test.jsx
import { render, screen } from '@testing-library/react';
import { MyComponent } from './MyComponent';
describe('MyComponent labels', () => {
test('displays the first label', () => {
render(<MyComponent label="Hello" />);
expect(screen.getByText('Hello')).toBeInTheDocument();
});
test('displays a different label', () => {
render(<MyComponent label="Welcome" />);
expect(screen.getByText('Welcome')).toBeInTheDocument();
});
});
Run the tests with npm test or yarn test. This screenshot shows test output from an earlier CodeSandbox example:

A snapshot test compares a serialized value with a stored version. For a React component, you can snapshot the rendered DOM to review changes to its markup.
Hereâs a Link component and the App that hosts it:
// Link.jsx
const Link = ({ page }) => {
return (
<a
className='normal'
href={page}
onMouseEnter={() => console.log('Mouse enter')}
onMouseLeave={() => console.log('Mouse leave')}
>
My Domain
</a>
);
};
export default Link;
// App.jsx
import './index.css';
import Link from './Link';
export default function App() {
return (
<div className='App'>
<h1>Hello Codes</h1>
<Link page='https://example.com' />
</div>
);
}
React has deprecated react-test-renderer. React Testing Libraryâs asFragment() provides a DOM fragment that Jest can snapshot:
// Link.test.jsx
import { render } from '@testing-library/react'
import Link from './Link'
it('renders correctly', () => {
const { asFragment } = render(<Link page='https://example.com' />)
expect(asFragment()).toMatchSnapshot()
})
On the first local run, Jest creates a snapshot file alongside the test in a __snapshots__ directory:
// __snapshots__/Link.test.jsx.snap
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`renders correctly 1`] = `
<DocumentFragment>
<a
class="normal"
href="https://example.com"
>
My Domain
</a>
</DocumentFragment>
`;
On later runs, Jest fails the test if the rendered output differs from the stored snapshot. Review intentional changes before updating the snapshot.
The snapshot contains the anchorâs DOM markup. Event handlers such as onMouseEnter are absent from that markup, and a DOM snapshot doesnât capture the browserâs visual rendering. Test interactions and visual behavior separately.
Jest can replace functions and modules with mocks so you can control their behavior in a test. For example, letâs test a function that fetches customers through Axios:
npm install axios
// customers.js
import axios from 'axios'
export async function getCustomerByName(name) {
const { data } = await axios.get('/api/customers')
return data.find((customer) => customer.name === name)
}
Hereâs the test, with Axios replaced by a mock:
// customers.test.js
import axios from 'axios'
import { getCustomerByName } from './customers'
// the factory means Jest never loads the real axios package
jest.mock('axios', () => ({ get: jest.fn() }))
test('should fetch a customer by name', async () => {
const customers = [{ name: 'Bob' }, { name: 'Jenny' }]
axios.get.mockResolvedValue({ data: customers })
const customer = await getCustomerByName('Bob')
expect(customer).toEqual({ name: 'Bob' })
})
We simulate the API response with axios.get.mockResolvedValue({ data: customers }), then check that getCustomerByName('Bob') returns the matching customer. This example makes no network request.
The module-mocking example uses the Babel-based Jest setup above. Native ESM projects have a different Jest module-mocking workflow.
Created by Kent C. Dodds and maintained by contributors, React Testing Library provides utilities for testing components through their rendered output. Its queries encourage assertions based on how users find and interact with elements.
With React Testing Library, you can:
findBy queries or retry assertions with waitForThe library renders components into a DOM environment and provides no shallow-rendering API. Its queries operate on rendered elements without exposing a componentâs private state.
If you followed the Jest setup, the packages are already installed. Otherwise, add them to a project with a configured test runner:
npm install -D @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom
Now for a small component with a button that disables itself after one click:
// ClickOnce.jsx
import { useState } from 'react'
export function ClickOnce() {
const [clicked, setClicked] = useState(false)
return (
<button disabled={clicked} onClick={() => setClicked(true)}>
Click me
</button>
)
}
Hereâs the test:
// ClickOnce.test.jsx
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ClickOnce } from './ClickOnce'
describe('ClickOnce', () => {
test('disables the button after a click', async () => {
const user = userEvent.setup()
render(<ClickOnce />) // render the component to the DOM
await user.click(screen.getByRole('button', { name: 'Click me' })) // find the button and click it
expect(screen.getByRole('button')).toBeDisabled() // the test passes if the button is disabled
})
})
We render ClickOnce, click the button by its accessible name, and check that it becomes disabled. You can find the full API in the React Testing Library documentation.
For apps built with Vite, Vitest uses the Vite configuration and transforms, which avoids a separate Babel setup for these tests. The React Testing Library rendering and query APIs work with either runner.
Weâll test a NewsletterForm component with an email field and a submit button that stays disabled until the input matches a simple pattern. The form displays an error after the user leaves the field with invalid input.
The authorâs StackBlitz demo includes the jsdom examples. The Browser Mode example uses a locally installed Chromium browser.
Create React App is deprecated, so weâll use Vite for this standalone example. The Node.js version noted above meets the requirements of Vite and the test dependencies:
npm create vite@latest newsletter-demo -- --template react-ts cd newsletter-demo npm install npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom
Vitest runs the tests, and jsdom provides a simulated DOM in Node.js. React Testing Library renders components; user-event simulates interactions, and jest-dom supplies matchers such as toBeDisabled(). The installation includes @testing-library/dom, a peer dependency of React Testing Library v16.
Add a test block to vite.config.ts:
// vite.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: './src/setupTests.ts',
},
});
With globals: true, React Testing Library can register its automatic cleanup through the global afterEach hook. If you prefer explicit imports and leave globals disabled, register afterEach(cleanup) in your setup file instead, following the cleanup instructions.
For TypeScript, add vitest/globals to the existing compilerOptions.types array in tsconfig.app.json. Preserve other entries, such as vite/client.
Create the setup file that loads the jest-dom matchers:
// src/setupTests.ts import '@testing-library/jest-dom/vitest'
Run npx vitest for watch mode during local development. Use npx vitest run for a single run, including in CI.
The component enables submission when the email matches a simple pattern and displays an error after the field loses focus with invalid input:
// src/NewsletterForm.tsx
import { useState } from 'react'
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
type Props = { onSubmit: (email: string) => void }
export function NewsletterForm({ onSubmit }: Props) {
const [email, setEmail] = useState('')
const [touched, setTouched] = useState(false)
const isValid = EMAIL_PATTERN.test(email)
return (
<form
onSubmit={(e) => {
e.preventDefault()
if (isValid) onSubmit(email)
}}
>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
onBlur={() => setTouched(true)}
/>
{touched && !isValid && (
<p role="alert" className="error">
Enter a valid email address
</p>
)}
<button type="submit" disabled={!isValid}>
Subscribe
</button>
</form>
)
}
The pattern is a basic format check. Your server still needs to validate submissions, and confirming that an address receives email requires a separate verification step.
Now the test. The imports identify which package handles each part:
// src/NewsletterForm.test.tsx
import { render, screen } from '@testing-library/react' // renderer + queries
import userEvent from '@testing-library/user-event' // realistic typing and clicking
import { expect, test, vi } from 'vitest' // runner, assertions, mocks
import { NewsletterForm } from './NewsletterForm'
test('keeps the button disabled until the email is valid', async () => {
const user = userEvent.setup()
render(<NewsletterForm onSubmit={vi.fn()} />)
const button = screen.getByRole('button', { name: /subscribe/i })
expect(button).toBeDisabled()
await user.type(screen.getByLabelText(/email/i), '[email protected]')
expect(button).toBeEnabled()
})
test('submits the email', async () => {
const user = userEvent.setup()
const onSubmit = vi.fn()
render(<NewsletterForm onSubmit={onSubmit} />)
await user.type(screen.getByLabelText(/email/i), '[email protected]')
await user.click(screen.getByRole('button', { name: /subscribe/i }))
expect(onSubmit).toHaveBeenCalledWith('[email protected]')
})
test('shows an error after leaving an invalid email', async () => {
const user = userEvent.setup()
render(<NewsletterForm onSubmit={vi.fn()} />)
await user.type(screen.getByLabelText(/email/i), 'nope')
await user.tab() // moves focus away, which triggers onBlur
expect(screen.getByRole('alert')).toHaveTextContent(
'Enter a valid email address'
)
})
test, expect, and vi.fn() come from Vitest. React Testing Library supplies render and screen, and user-event handles the simulated interactions.
To adapt this example to Jest, update the runner imports, replace vi.fn() with jest.fn(), and use the Jest matcher setup shown earlier. The queries and component assertions can stay the same.
These tests check validation and submission behavior in jsdom. They leave the formâs browser rendering untested.
jsdom implements many DOM APIs, including basic focus behavior, but it does not perform browser layout or visual rendering. Vitest also bypasses CSS processing in its default Node-based configuration unless you enable it.
A DOM test that checks only an error messageâs text can pass even when a stylesheet hides that message. A browser test can check its visibility with the applicationâs CSS applied.
Vitest Browser Mode became stable in v4.0. With the Playwright provider, it runs tests in Chromium, Firefox, or WebKit. Install the provider and React renderer, keeping the providerâs version aligned with Vitest:
npm install -D @vitest/browser-playwright vitest-browser-react npx playwright install chromium
Keep browser tests in their own configuration so you can run them separately from jsdom tests. Create vitest.browser.config.ts:
import { defineConfig } from 'vitest/config'
import { playwright } from '@vitest/browser-playwright'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
include: ['src/**/*.browser.test.tsx'],
browser: {
enabled: true,
headless: true, // run without a visible browser window
provider: playwright(),
instances: [{ browser: 'chromium' }],
},
},
})
Next, prevent the jsdom suite from collecting browser tests. Import configDefaults in vite.config.ts and add this exclude entry inside its test block:
import { configDefaults } from 'vitest/config'
// inside defineConfig({ test: { ... } })
exclude: [...configDefaults.exclude, '**/*.browser.test.tsx', 'e2e/**'],
Add these entries to the existing scripts object in package.json:
{
"scripts": {
"test": "vitest",
"test:browser": "vitest --config vitest.browser.config.ts"
}
}
The browser test imports src/index.css so your applicationâs styles apply. For this example, add .error { color: #b00020; } to that stylesheet:
// src/NewsletterForm.browser.test.tsx
import { expect, test, vi } from 'vitest'
import { page, userEvent } from 'vitest/browser'
import { render } from 'vitest-browser-react'
import { NewsletterForm } from './NewsletterForm'
import './index.css' // apply the application stylesheet
test('shows a visible error after leaving an invalid email', async () => {
await render(<NewsletterForm onSubmit={vi.fn()} />)
await page.getByLabelText('Email').fill('nope')
await userEvent.tab()
// check visibility with the stylesheet applied
await expect.element(page.getByRole('alert')).toBeVisible()
})
This example uses Vitestâs browser APIs in several places:
page locatorsexpect.element() retries the DOM assertion until it passes or times outuserEvent comes from vitest/browser and sends input through the configured browser providerThe visibility assertion checks the element in a real browser. It does not replace visual regression tests for details such as color or spacing.
Browser tests add browser startup and installation requirements. In CI, install the browser and its system dependencies with npx playwright install --with-deps chromium, then run npm run test:browser -- --run.
Use jsdom for tests that need DOM behavior without browser rendering. Choose Browser Mode when layout, focus behavior, or browser APIs affect the feature youâre testing.
Unit and component integration tests cover parts of the application. End-to-end tests let you verify important workflows through a running app and its backend before release.
Cypress and Playwright both support browser-based end-to-end tests. The login examples below illustrate their APIs and assume an application with a login link, a /login route, and an email input with the class email. Those elements are separate from the newsletter component above.
Cypress includes a test runner and assertions, so you can write end-to-end tests without adding another testing framework. It supports Firefox and Chromium-based browsers such as Chrome and Edge.
Cypress provides:
Install and open Cypress:
npm install -D cypress npx cypress open
Select E2E Testing and complete the configuration steps. Start your appâs development server separately, then create cypress/e2e/login.cy.js:
// cypress/e2e/login.cy.js
describe('Login navigation', () => {
it('opens the login page and accepts an email', () => {
cy.visit('http://localhost:5173');
cy.contains(/^log in$/i).click();
cy.url().should('include', '/login');
cy.get('.email')
.type('[email protected]')
.should('have.value', '[email protected]');
});
});
Update the URL and selectors to match your app. This example checks navigation and text entry; a complete login test would also submit credentials and assert the authenticated result.
Cypress can also mount a single component in a real browser. If your team already uses Cypress, its React component testing can share the same testing workflow.
Playwright Test supports Chromium, Firefox, and WebKit. It provides automatic waiting and a trace viewer for inspecting recorded test runs.
Set it up with npm init playwright@latest. Choose e2e as the test directory during setup, or set testDir: './e2e' in the generated playwright.config.ts, then write the same navigation and input check:
// e2e/login.spec.ts
import { test, expect } from '@playwright/test';
test('opens the login page and accepts an email', async ({ page }) => {
await page.goto('http://localhost:5173');
await page.getByRole('link', { name: /^log in$/i }).click();
await expect(page).toHaveURL(/\/login/);
const email = page.locator('.email');
await email.fill('[email protected]');
await expect(email).toHaveValue('[email protected]');
});
Start the appâs development server before running npx playwright test, or configure Playwrightâs webServer option to start it for you. Playwrightâs test code uses async and await for browser actions and retrying assertions.
If the end-to-end specs live in the same project as your component tests, exclude e2e/** from Jest or Vitestâs test discovery. Each suite should run through its intended runner.
For a new Vite app, start with Vitest and React Testing Library, then add browser coverage for behavior that depends on the browser. Keep an existing Jest suite if it meets your needs; a migration should solve a specific problem in your project.
| Your situation | Suggested tools | Why |
|---|---|---|
| New Vite app | Vitest and React Testing Library; Cypress or Playwright for critical end-to-end flows | Reuse Viteâs transforms and configuration for component tests |
| Components that depend on CSS, layout, or browser focus behavior | Vitest Browser Mode | Test in a real browser while keeping Vitest as the runner |
| Existing Jest and React Testing Library suite | Keep the suite; add browser coverage where needed | Preserve working tests and avoid unnecessary migration work |
| React Native app | Jest and React Native Testing Library | Use renderers and queries designed for native components |
| Existing Cypress end-to-end suite | Consider Cypress component testing | Reuse Cypressâs commands and debugging workflow |
| Existing Enzyme suite | Plan a migration to React Testing Library | Enzymeâs official adapters cover older React releases; community adapters require separate compatibility checks |
See the React Native testing guide for native applications and Enzymeâs adapter list when evaluating an older suite.
Choose your React testing tools around the behavior you need to verify. Vitest and React Testing Library fit Vite-based component tests, and Jest remains a practical choice for an established suite.
Add real-browser component tests for browser-dependent behavior and end-to-end tests for important workflows. You can expand that coverage as you identify gaps in your applicationâs tests.
Install LogRocket via npm or script tag. LogRocket.init() must be called client-side, not
server-side
$ npm i --save logrocket
// Code:
import LogRocket from 'logrocket';
LogRocket.init('app/id');
// Add to your HTML:
<script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
<script>window.LogRocket && window.LogRocket.init('app/id');</script>

Explore Git-driven agentic workflows with PatchPup and Fullsend, covering automation, CI checks, pull requests, and best practices for scaling AI coding agents.

Building the same support assistant with React Spectrum, Vercel AI Elements, and CopilotKit reveals differences in setup and UI control. Compare the code and integration work to choose an approach for your React app.

Can React Resizable Panelsâ Workspace replace Dockview or FlexLayout? Compare bundle size, tab state, and accessibility.

Learn to build a Python-based PDF search app with Typesense, embeddings, and semantic retrieval.
Would you be interested in joining LogRocket's developer community?
Join LogRocketâs Content Advisory Board. Youâll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up now