| How to Test React Components with React Testing Library :👈 | 👉:How to Test Forms in React |
How to Test User Interactions in React |
How to Test User Interactions in React
1. Introduction
User interaction testing verifies that React components behave correctly when users interact with the application.
In a real application, users perform actions such as:
- Clicking buttons.
- Typing into input fields.
- Submitting forms.
- Selecting dropdown options.
- Checking and unchecking checkboxes.
- Opening and closing modals.
- Navigating between pages.
- Adding products to a shopping cart.
We use React Testing Library and user-event to simulate these interactions and verify the expected UI behavior.
2. Tools Required
| Tool | Purpose |
|---|---|
| React Testing Library | Render React components and query the DOM. |
| user-event | Simulate realistic user interactions. |
| Vitest | Run tests and provide assertions and mocking. |
| jest-dom | Provide convenient DOM assertions. |
| jsdom | Provide a simulated browser DOM environment. |
Install the dependencies for a Vite-based React application:
npm install -D vitest jsdom
npm install -D @testing-library/react
npm install -D @testing-library/user-event
npm install -D @testing-library/jest-dom
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 src/test/setup.js:
import "@testing-library/jest-dom/vitest";
3. Understanding user-event
user-event is a library that simulates user interactions more realistically than directly dispatching individual DOM events.
Import it into the test file:
import userEvent from "@testing-library/user-event";
Create a user instance inside the test:
const user = userEvent.setup();
Common interaction methods:
| Method | Purpose |
|---|---|
| user.click() | Click a button or other interactive element. |
| user.type() | Type text into an input field. |
| user.clear() | Clear an input field. |
| user.selectOptions() | Select an option from a dropdown. |
| user.deselectOptions() | Deselect options in a multiple-select element. |
| user.keyboard() | Simulate keyboard input. |
| user.tab() | Move keyboard focus. |
| user.hover() | Move the pointer over an element. |
| user.unhover() | Move the pointer away from an element. |
| user.upload() | Select a file for a file input. |
Most user-event operations are asynchronous, so use await.
4. Testing Button Clicks
Consider a counter component. Clicking the button should increase the count.
Counter.jsx
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default Counter;
Counter.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./Counter";
test("increments count when button is clicked", async () => {
const user = userEvent.setup();
render(<Counter />);
expect(screen.getByText("Count: 0")).toBeInTheDocument();
await user.click(
screen.getByRole("button", { name: "Increment" })
);
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});
What are we testing?
- The initial count is zero.
- The user clicks the Increment button.
- The displayed count changes to one.
5. Testing Input Field Interactions
Consider a search box where users enter a product name.
SearchBox.jsx
import { useState } from "react";
function SearchBox() {
const [search, setSearch] = useState("");
return (
<div>
<label htmlFor="product-search">
Search Product
</label>
<input
id="product-search"
value={search}
onChange={e => setSearch(e.target.value)}
/>
<p>Search: {search}</p>
</div>
);
}
export default SearchBox;
SearchBox.test.jsx
test("updates search text when user types", async () => {
const user = userEvent.setup();
render(<SearchBox />);
const input = screen.getByRole("textbox", {
name: "Search Product"
});
await user.type(input, "Laptop");
expect(input).toHaveValue("Laptop");
expect(
screen.getByText("Search: Laptop")
).toBeInTheDocument();
});
6. Testing Form Submission
Consider a registration form that validates user input and displays a success message.
RegistrationForm.jsx
import { useState } from "react";
function RegistrationForm() {
const [name, setName] = useState("");
const [message, setMessage] = useState("");
function handleSubmit(event) {
event.preventDefault();
if (!name.trim()) {
setMessage("Name is required");
return;
}
setMessage("Registration successful");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name</label>
<input
id="name"
value={name}
onChange={e => setName(e.target.value)}
/>
<button type="submit">Register</button>
{message && <p role="status">{message}</p>}
</form>
);
}
export default RegistrationForm;
RegistrationForm.test.jsx
test("displays validation message for empty name", async () => {
const user = userEvent.setup();
render(<RegistrationForm />);
await user.click(
screen.getByRole("button", { name: "Register" })
);
expect(
screen.getByText("Name is required")
).toBeInTheDocument();
});
test("submits form successfully", async () => {
const user = userEvent.setup();
render(<RegistrationForm />);
await user.type(
screen.getByRole("textbox", { name: "Name" }),
"John"
);
await user.click(
screen.getByRole("button", { name: "Register" })
);
expect(
screen.getByText("Registration successful")
).toBeInTheDocument();
});
7. Testing Dropdown Selection
Consider a product category dropdown.
CategorySelect.jsx
import { useState } from "react";
function CategorySelect() {
const [category, setCategory] = useState("");
return (
<div>
<label htmlFor="category">Category</label>
<select
id="category"
value={category}
onChange={e => setCategory(e.target.value)}
>
<option value="">Select category</option>
<option value="electronics">Electronics</option>
<option value="clothing">Clothing</option>
</select>
<p>Selected: {category}</p>
</div>
);
}
export default CategorySelect;
CategorySelect.test.jsx
test("allows user to select a category", async () => {
const user = userEvent.setup();
render(<CategorySelect />);
const dropdown = screen.getByRole("combobox", {
name: "Category"
});
await user.selectOptions(dropdown, "electronics");
expect(dropdown).toHaveValue("electronics");
expect(
screen.getByText("Selected: electronics")
).toBeInTheDocument();
});
8. Testing Checkboxes
Consider a checkbox that allows users to accept terms and conditions.
Terms.jsx
import { useState } from "react";
function Terms() {
const [accepted, setAccepted] = useState(false);
return (
<div>
<label>
<input
type="checkbox"
checked={accepted}
onChange={e => setAccepted(e.target.checked)}
/>
Accept Terms and Conditions
</label>
<p>{accepted ? "Accepted" : "Not accepted"}</p>
</div>
);
}
export default Terms;
Terms.test.jsx
test("allows user to accept terms", async () => {
const user = userEvent.setup();
render(<Terms />);
const checkbox = screen.getByRole("checkbox", {
name: "Accept Terms and Conditions"
});
expect(checkbox).not.toBeChecked();
await user.click(checkbox);
expect(checkbox).toBeChecked();
expect(screen.getByText("Accepted")).toBeInTheDocument();
});
9. Testing Keyboard Interactions
Users may navigate and operate applications using a keyboard instead of a mouse.
React Testing Library allows us to test keyboard interactions with user.keyboard() and user.tab().
KeyboardExample.jsx
function KeyboardExample() {
return (
<div>
<label htmlFor="username">Username</label>
<input id="username" />
<button>Submit</button>
</div>
);
}
export default KeyboardExample;
KeyboardExample.test.jsx
test("supports keyboard navigation", async () => {
const user = userEvent.setup();
render(<KeyboardExample />);
const input = screen.getByRole("textbox", {
name: "Username"
});
const button = screen.getByRole("button", {
name: "Submit"
});
await user.tab();
expect(input).toHaveFocus();
await user.tab();
expect(button).toHaveFocus();
});
This verifies that users can navigate between interactive elements using the Tab key.
10. Testing Modal Open and Close Interactions
Consider a modal that opens when a user clicks a button.
Modal.jsx
import { useState } from "react";
function Modal() {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(true)}>
Open Modal
</button>
{open && (
<div role="dialog" aria-modal="true"
aria-labelledby="modal-title">
<h2 id="modal-title">Confirm Action</h2>
<p>Are you sure?</p>
<button onClick={() => setOpen(false)}>
Close
</button>
</div>
)}
</div>
);
}
export default Modal;
Modal.test.jsx
test("opens and closes modal", async () => {
const user = userEvent.setup();
render(<Modal />);
await user.click(
screen.getByRole("button", { name: "Open Modal" })
);
expect(
screen.getByRole("dialog")
).toBeInTheDocument();
await user.click(
screen.getByRole("button", { name: "Close" })
);
expect(
screen.queryByRole("dialog")
).not.toBeInTheDocument();
});
11. Testing Hover Interactions
Hover interactions are commonly used for tooltips and dropdown menus.
Tooltip.jsx
import { useState } from "react";
function Tooltip() {
const [visible, setVisible] = useState(false);
return (
<div>
<button
onMouseEnter={() => setVisible(true)}
onMouseLeave={() => setVisible(false)}
>
Help
</button>
{visible && <p role="tooltip">Helpful information</p>}
</div>
);
}
export default Tooltip;
Tooltip.test.jsx
test("displays tooltip on hover", async () => {
const user = userEvent.setup();
render(<Tooltip />);
const button = screen.getByRole("button", {
name: "Help"
});
await user.hover(button);
expect(
screen.getByRole("tooltip")
).toBeInTheDocument();
await user.unhover(button);
expect(
screen.queryByRole("tooltip")
).not.toBeInTheDocument();
});
12. Testing File Uploads
File upload testing verifies that users can select a file and that the component responds correctly.
FileUpload.jsx
import { useState } from "react";
function FileUpload() {
const [fileName, setFileName] = useState("");
return (
<div>
<label htmlFor="file">Upload File</label>
<input
id="file"
type="file"
onChange={e => {
setFileName(e.target.files[0]?.name || "");
}}
/>
{fileName && <p>Selected: {fileName}</p>}
</div>
);
}
export default FileUpload;
FileUpload.test.jsx
test("allows user to select a file", async () => {
const user = userEvent.setup();
render(<FileUpload />);
const file = new File(
["sample content"],
"sample.txt",
{ type: "text/plain" }
);
await user.upload(
screen.getByLabelText("Upload File"),
file
);
expect(
screen.getByText("Selected: sample.txt")
).toBeInTheDocument();
});
13. Testing Navigation Interactions
When an application uses React Router, render the component inside a router during testing.
For example, you can use MemoryRouter and Routes to test navigation without opening a real browser.
Navigation.jsx
import { Link, Route, Routes } from "react-router-dom";
function Navigation() {
return (
<>
<nav>
<Link to="/products">Products</Link>
</nav>
<Routes>
<Route
path="/products"
element={<h2>Products Page</h2>}
/>
</Routes>
</>
);
}
export default Navigation;
Navigation.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import Navigation from "./Navigation";
test("navigates to products page", async () => {
const user = userEvent.setup();
render(
<MemoryRouter>
<Navigation />
</MemoryRouter>
);
await user.click(
screen.getByRole("link", { name: "Products" })
);
expect(
screen.getByRole("heading", {
name: "Products Page"
})
).toBeInTheDocument();
});
14. Testing Interactions with API Calls
Consider an Add to Cart button. Clicking it should call a service and display a success message.
Cart.jsx
import { useState } from "react";
import { addToCart } from "./cartService";
function Cart({ product }) {
const [message, setMessage] = useState("");
async function handleAddToCart() {
await addToCart(product.id);
setMessage("Product added to cart");
}
return (
<div>
<h2>{product.name}</h2>
<button onClick={handleAddToCart}>
Add to Cart
</button>
{message && <p role="status">{message}</p>}
</div>
);
}
export default Cart;
Cart.test.jsx
import { vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Cart from "./Cart";
import { addToCart } from "./cartService";
vi.mock("./cartService", () => ({
addToCart: vi.fn()
}));
test("adds product to cart when button is clicked", async () => {
const user = userEvent.setup();
addToCart.mockResolvedValue({ success: true });
render(
<Cart product={{ id: 1, name: "Laptop" }} />
);
await user.click(
screen.getByRole("button", { name: "Add to Cart" })
);
expect(addToCart).toHaveBeenCalledWith(1);
expect(
await screen.findByRole("status")
).toHaveTextContent("Product added to cart");
});
This test verifies both the user interaction and its visible result, while mocking the external API service.
In production code, also handle API failures and prevent misleading success messages when the request fails.
15. fireEvent vs user-event
Both libraries can trigger DOM events, but they serve slightly different purposes.
| Feature | fireEvent | user-event |
|---|---|---|
| Purpose | Dispatch individual DOM events. | Simulate user interactions. |
| Typing | Can dispatch change or input events directly. | Simulates typing behavior. |
| Clicking | Dispatches a click event. | Simulates a more realistic click interaction. |
| Asynchronous API | Usually synchronous. | Most interactions return Promises. |
| Recommended usage | Specific low-level event scenarios. | Most normal user interactions. |
Recommendation: Prefer user-event for everyday user interaction tests. Use fireEvent when you specifically need to dispatch an individual event that user-event does not conveniently model.
16. Common Mistakes in User Interaction Testing
| Mistake | Better Approach |
|---|---|
| Forgetting await with user-event | Await asynchronous interactions. |
| Using test IDs for every element | Prefer accessible roles and labels. |
| Testing internal state directly | Verify visible UI behavior. |
| Using getBy for asynchronous elements | Use findBy queries. |
| Testing only successful interactions | Include validation and failure scenarios. |
| Using arbitrary delays | Use findBy or waitFor. |
| Mocking the entire component unnecessarily | Test the actual component and mock only appropriate external dependencies. |
17. Recommended Best Practices
- Use
userEvent.setup()to create a user instance. - Use
awaitwith user-event interactions. - Prefer
getByRole()andgetByLabelText(). - Test what users can see and do.
- Test both successful and unsuccessful interactions.
- Verify the visible result after every important interaction.
- Test keyboard navigation and accessibility where relevant.
- Mock external API dependencies instead of relying on a live backend.
- Keep tests independent and easy to understand.
- Avoid testing React's internal implementation details.
18. Interview Questions and Answers
Q1. What is user interaction testing in React?
It verifies that components respond correctly to actions such as clicking, typing, selecting options, submitting forms, and navigating.
Q2. What is user-event?
user-event is a Testing Library utility that simulates realistic user interactions with DOM elements.
Q3. What is the difference between user-event and fireEvent?
user-event simulates higher-level user interactions, whereas fireEvent dispatches individual DOM events directly.
Q4. Why should we use await with user-event?
Most user-event operations are asynchronous and return Promises. Awaiting them ensures that the interaction completes before assertions are made.
Q5. How do you test a button click?
Render the component, locate the button using getByRole(), click it using user.click(), and verify the resulting UI.
Q6. How do you test form validation?
Enter valid or invalid values, submit the form, and verify that the correct validation messages or success messages appear.
Q7. How do you test dropdown selection?
Find the dropdown using getByRole("combobox") and use user.selectOptions() to select an option.
Q8. How do you test modal interactions?
Click the button that opens the modal, verify that the dialog appears, click the close button, and verify that the dialog is removed.
Q9. How do you test keyboard accessibility?
Use user.tab() and user.keyboard() to simulate keyboard navigation and verify focus and expected behavior.
Q10. Should user interaction tests call real APIs?
Usually, component tests should mock external API boundaries to remain predictable. Separate integration or end-to-end tests can verify communication with actual services in a controlled environment.
19. Key Takeaways
- React Testing Library helps test React components from the user's perspective.
user-eventis preferred for realistic user interactions.- Test button clicks, typing, forms, dropdowns, checkboxes, keyboard actions, modals, and navigation.
- Use accessible queries such as
getByRole()andgetByLabelText(). - Use
findBy...for asynchronous UI updates. - Verify the visible outcome rather than inspecting internal component state.
- Include success, validation, and error scenarios.
Final takeaway: A good user interaction test follows the same steps as a real user: find an element, interact with it, and verify the result. This makes React tests meaningful, maintainable, and closer to real application behavior.
| How to Test React Components with React Testing Library :👈 | 👉:How to Test Forms in React |
Comments and Discussion