user-event is a Testing Library library for simulating user interactions in automated React tests. It replaces direct DOM methods with interactions such as clicking, typing, hovering, and dragging. section 10.2.1
Use user-event to:
- Create a user with userEvent.setup(), locate controls by accessible roles, and await interactions such as user.click(button). section 10.2.1
- Type into inputs with user.type(), exercising focus, character input, and change handling rather than updating component state directly. section 10.2.3
- Prefer user-event for ordinary interactions; use React Testing Library’s lower-level fireEvent for specialized cases it does not cover. section 10.2.3
Testing a counter
Render Counter, create a user, find the Increment button by role, await user.click(increment), and assert that the heading reads “Counter: 1”. The same pattern tests decrementing while keeping assertions focused on visible behavior. section 10.2.1
Testing a timer form
Find the minutes and seconds spinbuttons and the Start button, type values into both fields, click Start, and verify that the callback receives the resulting duration. Avoid asserting the component’s internal state representation. section 10.2.3
Listing 10.5 Clicking a button
import { render, screen } from "@testing-library/react";
import userEvent
from "@testing-library/user-event"; #1
import "@testing-library/jest-dom";
import { Counter } from "./Counter";
test( #2
"Counter should start at the given value", #2
() => {...}, #2
); #2
test( #2
"Counter should start at 0 if no value is given", #2
() => {...}, #2
); #2
test( #3
"Counter should increment when button is clicked", #3
async () => { #3
// ARRANGE
render(<Counter />);
// ACT
const user = userEvent.setup(); #4
const increment = screen.getByRole( #5
"button", #5
{ name: "Increment" }, #5
); #5
await user.click(increment); #6
// ASSERT
const heading = screen.getByRole( #7
"heading", #7
{ name: "Counter: 1" }, #7
); #7
expect(heading).toBeInTheDocument();
});
Shows the complete setup-and-click pattern, including accessible queries, userEvent.setup(), asynchronous interaction, and a visible assertion. section 10.2.1
