| Common React Architecture Mistakes :👈 | 👉:How to Test User Interactions in React |
How to Test React Components with React Testing Library |
How to Test React Components with React Testing Library
1. What Is React Testing Library?
React Testing Library (RTL) is a testing library used to test React components from the user's perspective.
Instead of testing internal implementation details such as component state, internal methods, or React component instances, it focuses on what users can see and do.
For example, consider a Login component. We can test:
- Whether the username and password fields are displayed.
- Whether the Login button is available.
- Whether users can enter their credentials.
- Whether clicking Login displays the expected result.
- Whether validation messages appear for invalid input.
React Testing Library is commonly used with Jest or Vitest and a DOM testing environment such as jsdom.
2. Why Use React Testing Library?
- User-focused testing: Tests how users interact with the application.
- Maintainability: Tests are less dependent on internal component implementation.
- Confidence: Helps identify problems before deployment.
- Accessibility: Encourages selecting elements using accessible roles and labels.
- Integration testing: Allows testing multiple components working together.
3. Important Testing Libraries
| Library | Purpose |
|---|---|
| React Testing Library | Render React components and interact with their DOM. |
| Vitest | Test runner, assertions, mocking, and test execution. |
| Jest | Test runner, assertions, and mocking. |
| user-event | Simulate realistic user interactions such as typing and clicking. |
| jest-dom | Provides convenient DOM assertions such as toBeInTheDocument(). |
| jsdom | Provides a browser-like DOM environment for tests. |
4. Installing React Testing Library
For a React application using Vite and Vitest, install the following development dependencies:
npm install -D vitest jsdom
npm install -D @testing-library/react
npm install -D @testing-library/jest-dom
npm install -D @testing-library/user-event
These packages provide the test runner, simulated DOM, React rendering utilities, DOM assertions, and user interaction helpers.
Configure Vitest in vite.config.js
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
setupFiles: "./src/test/setup.js",
globals: true
}
});
Create the test setup file
src/test/setup.js
import "@testing-library/jest-dom/vitest";
This makes DOM assertions available in your tests.
Add test scripts to package.json
{
"scripts": {
"dev": "vite",
"build": "vite build",
"test": "vitest",
"test:run": "vitest run"
}
}
Run tests using:
npm test
5. Understanding the Basic Testing Structure
A typical React Testing Library test follows four steps:
- Arrange: Prepare the component and test data.
- Act: Perform a user interaction.
- Assert: Verify the expected result.
- Cleanup: Remove rendered components after the test. React Testing Library normally handles this automatically when the test environment supports it.
Example:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
test("shows a welcome message after clicking", async () => {
// Arrange
const user = userEvent.setup();
render(<Welcome />);
// Act
await user.click(
screen.getByRole("button", { name: /welcome/i })
);
// Assert
expect(
screen.getByText("Welcome to React!")
).toBeInTheDocument();
});
6. Example 1: Testing a Simple React Component
Consider a component that displays a heading and a button.
Welcome.jsx
import { useState } from "react";
function Welcome() {
const [message, setMessage] = useState("");
return (
<div>
<h1>Welcome Page</h1>
<button onClick={() => setMessage("Welcome to React!")}>
Show Welcome
</button>
{message && <p>{message}</p>}
</div>
);
}
export default Welcome;
Welcome.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Welcome from "./Welcome";
test("displays the welcome heading", () => {
render(<Welcome />);
expect(
screen.getByRole("heading", {
name: "Welcome Page"
})
).toBeInTheDocument();
});
test("displays the welcome message after clicking", async () => {
const user = userEvent.setup();
render(<Welcome />);
await user.click(
screen.getByRole("button", {
name: "Show Welcome"
})
);
expect(
screen.getByText("Welcome to React!")
).toBeInTheDocument();
});
What are we testing?
- The heading is displayed correctly.
- The button is available.
- Clicking the button displays the welcome message.
7. Understanding render(), screen(), and fireEvent()
render()
render() renders a React component into a simulated DOM environment for testing.
render(<Welcome />);
screen
screen provides queries to locate elements in the rendered DOM.
screen.getByText("Welcome Page");
screen.getByRole("button");
screen.getByLabelText("Username");
fireEvent
fireEvent dispatches DOM events directly.
import { fireEvent } from "@testing-library/react";
fireEvent.click(screen.getByRole("button"));
For most user interactions, user-event is generally preferred because it simulates more realistic interaction sequences, including events associated with typing and clicking.
8. Understanding Different Query Methods
React Testing Library provides different query methods to find elements.
| Query | Behavior | When to Use |
|---|---|---|
| getBy... | Returns one matching element or throws an error. | Element should already exist. |
| queryBy... | Returns one matching element or null. | Checking whether an element is absent. |
| findBy... | Returns a Promise and waits for an element to appear. | Asynchronous UI updates. |
| getAllBy... | Returns all matching elements or throws if none exist. | Multiple matching elements are expected. |
| queryAllBy... | Returns all matching elements or an empty array. | Checking multiple optional elements. |
| findAllBy... | Waits for multiple matching elements. | Asynchronous lists. |
Example: getByRole()
const button = screen.getByRole("button", {
name: "Submit"
});
Example: queryByText()
expect(
screen.queryByText("Invalid username")
).not.toBeInTheDocument();
Example: findByText()
const message = await screen.findByText(
"Data loaded successfully"
);
expect(message).toBeInTheDocument();
9. Recommended Query Priority
React Testing Library recommends selecting elements in ways that reflect how users and assistive technologies find them.
A useful priority order is:
getByRole()– Find elements by accessible role and name.getByLabelText()– Find form controls using their labels.getByPlaceholderText()– Find inputs using placeholder text.getByText()– Find elements using visible text.getByDisplayValue()– Find form elements using their current value.getByTestId()– Use a test-specific attribute when other queries are unsuitable.
Preferred:
screen.getByRole("button", {
name: "Submit"
});
Less preferred when a semantic query is available:
screen.getByTestId("submit-button");
10. Example 2: Testing Input Fields and Forms
Consider a login form with username and password fields.
Login.jsx
import { useState } from "react";
function Login() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [message, setMessage] = useState("");
function handleSubmit(event) {
event.preventDefault();
if (!username || !password) {
setMessage("Please enter all fields");
return;
}
setMessage("Login successful");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="username">Username</label>
<input
id="username"
value={username}
onChange={e => setUsername(e.target.value)}
/>
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
/>
<button type="submit">Login</button>
{message && <p role="status">{message}</p>}
</form>
);
}
export default Login;
Login.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Login from "./Login";
test("shows validation message for empty fields", async () => {
const user = userEvent.setup();
render(<Login />);
await user.click(
screen.getByRole("button", { name: "Login" })
);
expect(
screen.getByText("Please enter all fields")
).toBeInTheDocument();
});
test("logs in when both fields are entered", async () => {
const user = userEvent.setup();
render(<Login />);
await user.type(
screen.getByLabelText("Username"),
"john"
);
await user.type(
screen.getByLabelText("Password"),
"password123"
);
await user.click(
screen.getByRole("button", { name: "Login" })
);
expect(
screen.getByText("Login successful")
).toBeInTheDocument();
});
This verifies the form from the user's perspective without accessing the component's internal state.
11. Example 3: Testing API Calls
React components often retrieve data from backend APIs. We can test these components by mocking the API dependency.
ProductList.jsx
import { useEffect, useState } from "react";
import { getProducts } from "./productService";
function ProductList() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function loadProducts() {
try {
const data = await getProducts();
setProducts(data);
} finally {
setLoading(false);
}
}
loadProducts();
}, []);
if (loading) {
return <p>Loading products...</p>;
}
if (products.length === 0) {
return <p>No products found</p>;
}
return (
<ul>
{products.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
export default ProductList;
ProductList.test.jsx
import { render, screen } from "@testing-library/react";
import { vi } from "vitest";
import ProductList from "./ProductList";
import { getProducts } from "./productService";
vi.mock("./productService", () => ({
getProducts: vi.fn()
}));
test("displays products returned by API", async () => {
getProducts.mockResolvedValue([
{ id: 1, name: "Laptop" },
{ id: 2, name: "Mobile" }
]);
render(<ProductList />);
expect(
screen.getByText("Loading products...")
).toBeInTheDocument();
expect(
await screen.findByText("Laptop")
).toBeInTheDocument();
expect(
screen.getByText("Mobile")
).toBeInTheDocument();
});
What are we testing?
- The loading message appears initially.
- The mocked API returns product data.
- The products appear after the asynchronous operation completes.
Important: This example tests the component's behavior using a mocked service. It does not test the actual backend API.
12. Example 4: Testing API Error Handling
Extend the ProductList component to display an error message when the API request fails.
Updated ProductList.jsx
function ProductList() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
async function loadProducts() {
try {
const data = await getProducts();
setProducts(data);
} catch {
setError("Unable to load products");
} finally {
setLoading(false);
}
}
loadProducts();
}, []);
if (loading) return <p>Loading products...</p>;
if (error) return <p role="alert">{error}</p>;
if (products.length === 0) {
return <p>No products found</p>;
}
return (
<ul>
{products.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
Test the error scenario
test("displays an error when API request fails", async () => {
getProducts.mockRejectedValue(
new Error("Network error")
);
render(<ProductList />);
expect(
await screen.findByRole("alert")
).toHaveTextContent("Unable to load products");
});
13. Example 5: Testing Conditional Rendering
Consider a component that displays different content depending on whether a user is logged in.
UserProfile.jsx
function UserProfile({ user }) {
if (!user) {
return <p>Please log in</p>;
}
return <h2>Welcome, {user.name}</h2>;
}
export default UserProfile;
UserProfile.test.jsx
test("shows login message when user is not available", () => {
render(<UserProfile user={null} />);
expect(
screen.getByText("Please log in")
).toBeInTheDocument();
});
test("shows username when user is available", () => {
render(
<UserProfile user={{ name: "John" }} />
);
expect(
screen.getByRole("heading", {
name: "Welcome, John"
})
).toBeInTheDocument();
});
14. Testing Components That Use Context
If a component depends on Context, render it inside the appropriate provider.
ThemeContext.jsx
import { createContext, useContext } from "react";
const ThemeContext = createContext("light");
export function ThemeProvider({ children }) {
return (
<ThemeContext.Provider value="dark">
{children}
</ThemeContext.Provider>
);
}
export function ThemeMessage() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
ThemeMessage.test.jsx
test("displays the theme provided by Context", () => {
render(
<ThemeProvider>
<ThemeMessage />
</ThemeProvider>
);
expect(
screen.getByText("Current theme: dark")
).toBeInTheDocument();
});
For applications with several providers, create a reusable test wrapper that includes the providers required by the component.
15. Testing Asynchronous Operations
React applications frequently perform asynchronous operations such as API requests and delayed UI updates.
Use findBy... queries when waiting for an element to appear.
test("displays data after loading", async () => {
render(<ProductList />);
const product = await screen.findByText("Laptop");
expect(product).toBeInTheDocument();
});
Use waitFor() when you need to wait for an assertion or condition that is not conveniently represented by a single findBy query.
import { waitFor } from "@testing-library/react";
await waitFor(() => {
expect(getProducts).toHaveBeenCalledTimes(1);
});
Avoid unnecessary manual delays such as setTimeout inside tests. Prefer queries and utilities that wait for the expected condition.
16. Testing React Components with Jest
React Testing Library can also be used with Jest instead of Vitest.
Install the required packages:
npm install -D jest jest-environment-jsdom
npm install -D @testing-library/react
npm install -D @testing-library/jest-dom
npm install -D @testing-library/user-event
Configure Jest to use the jsdom environment and load the jest-dom setup file.
setupTests.js
import "@testing-library/jest-dom";
Example test:
import { render, screen } from "@testing-library/react";
import Welcome from "./Welcome";
test("renders welcome heading", () => {
render(<Welcome />);
expect(
screen.getByRole("heading", {
name: "Welcome Page"
})
).toBeInTheDocument();
});
The component testing approach remains almost the same. The main differences are the test runner configuration and mocking APIs.
17. Common React Testing Library Mistakes
| Mistake | Better Approach |
|---|---|
| Testing internal component state | Test visible UI behavior. |
| Using test IDs everywhere | Prefer accessible roles and labels. |
| Using getByText for elements that appear asynchronously | Use findByText. |
| Not awaiting user interactions | Await user-event operations. |
| Testing only successful API responses | Test loading, error, empty, and success states. |
| Mocking every dependency unnecessarily | Mock external boundaries when appropriate and test meaningful integration. |
| Using arbitrary setTimeout delays | Use findBy queries or waitFor. |
| Testing implementation details | Test behavior users can observe. |
18. What Should You Test in a React Application?
A practical testing checklist:
- Component rendering.
- Button clicks and user interactions.
- Form inputs and validation.
- Conditional rendering.
- Loading and error messages.
- API success and failure scenarios.
- Context and provider behavior.
- Navigation and routing behavior.
- Important business workflows.
- Accessibility-related behavior.
19. Unit Testing vs Integration Testing vs End-to-End Testing
| Testing Type | Purpose | Example |
|---|---|---|
| Unit Testing | Tests a small unit independently. | Testing a price calculation utility. |
| Integration Testing | Tests multiple parts working together. | Testing a form, validation, and mocked API interaction. |
| End-to-End Testing | Tests a complete user workflow in a browser. | Logging in and placing an order using a browser automation tool. |
React Testing Library is particularly useful for component-level and integration testing. Tools such as Playwright and Cypress are commonly used for end-to-end testing.
20. Recommended Best Practices
- Test components from the user's perspective.
- Prefer
getByRole()andgetByLabelText(). - Use
user-eventfor realistic interactions. - Use
findBy...for asynchronous UI updates. - Test loading, success, empty, and error states.
- Mock external API boundaries instead of depending on real backend availability in component tests.
- Avoid testing implementation details such as internal state variables.
- Keep tests independent and predictable.
- Use meaningful test descriptions.
- Test important user workflows rather than chasing 100% code coverage without considering test quality.
21. Interview Questions and Answers
Q1. What is React Testing Library?
React Testing Library is a library for testing React components by interacting with their rendered DOM in a way that resembles user behavior.
Q2. What is the difference between Jest and React Testing Library?
Jest is a test runner and assertion framework. React Testing Library provides utilities for rendering React components and querying their DOM. They can be used together.
Q3. What is the difference between getBy, queryBy, and findBy?
getBy throws if an element is missing, queryBy returns null when it is missing, and findBy waits asynchronously for an element to appear.
Q4. Why is user-event preferred over fireEvent?
user-event simulates more realistic user interactions, while fireEvent dispatches individual DOM events directly.
Q5. What is the purpose of render()?
render() mounts a React component into a test DOM so that its rendered output can be inspected and interacted with.
Q6. How do you test API calls in React?
Mock the API service or network boundary, provide controlled success or failure responses, and verify the resulting UI.
Q7. How do you test asynchronous components?
Use asynchronous queries such as findByText() and utilities such as waitFor() to wait for expected UI updates.
Q8. What is the purpose of jest-dom?
It provides convenient DOM matchers such as toBeInTheDocument(), toHaveTextContent(), and toBeVisible().
Q9. Should we test React component state directly?
Generally, no. Test the observable behavior produced by state changes rather than accessing internal state variables.
Q10. What is the difference between React Testing Library and Playwright?
React Testing Library focuses on component and DOM behavior within a test environment. Playwright automates real browsers and is commonly used for end-to-end testing.
22. Key Takeaways
- React Testing Library tests React components from the user's perspective.
- Vitest or Jest can be used as the test runner.
- Use
render()to render components andscreento query elements. - Prefer accessible queries such as
getByRole(). - Use
user-eventfor realistic interactions. - Use
findBy...andwaitFor()for asynchronous behavior. - Mock API dependencies to test success and failure scenarios.
- Focus on user-visible behavior instead of internal implementation details.
Final takeaway: A good React component test verifies what users can see and do. It should give confidence that the component behaves correctly without becoming tightly coupled to its internal implementation.
| Common React Architecture Mistakes :👈 | 👉:How to Test User Interactions in React |
Comments and Discussion