React / 74
Simulating clicks and typing with user-event
user-event clicks and types the way a real person does, firing the full chain of browser events. Always await it.
One click is many events
What one click really fires
Try itfireEvent.click(button) fires
clickand nothing else: no focus, no pointer events
your real click fired
Click (or tap) “Add Masala Dosa”.
Real users never fire just click. They move the pointer, press, focus, release. Some components depend on those other events (a dropdown that opens on mousedown, a form that validates on blur). fireEvent.click skips all of them; user.click replays them all.
The component
import { useState } from "react";
export default function DishSearch({ dishes }) {
const [query, setQuery] = useState("");
const [results, setResults] = useState(dishes);
function handleSubmit(e) {
e.preventDefault();
const q = query.toLowerCase();
setResults(dishes.filter((d) => d.toLowerCase().includes(q)));
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="q">Search dishes</label>
<input id="q" value={query} onChange={(e) => setQuery(e.target.value)} />
<button type="submit">Search</button>
<ul>
{results.map((d) => <li key={d}>{d}</li>)}
</ul>
</form>
);
}The test
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import DishSearch from "./DishSearch";
test("shows only matching dishes after a search", async () => {
const user = userEvent.setup();
render(<DishSearch dishes={["Veg Burger", "Paneer Pizza", "Chicken Burger"]} />);
expect(screen.getAllByRole("listitem")).toHaveLength(3);
await user.type(screen.getByLabelText("Search dishes"), "burger");
await user.click(screen.getByRole("button", { name: "Search" }));
expect(screen.getAllByRole("listitem")).toHaveLength(2);
expect(screen.queryByText("Paneer Pizza")).not.toBeInTheDocument();
});Set up a user
userEvent.setup()first, beforerender. It returns auserthat remembers things like which element is focused.Find, then act
Find the element with a query, thenawait user.type(...)orawait user.click(...).Assert what the user would see
Check the list, not theresultsstate.
The test function is async, and every user action is awaited: user-event fires its events asynchronously.
The actions you'll use
| Call | Does |
|---|---|
await user.click(el) | Pointer down/up, focus, click |
await user.dblClick(el) | Double click |
await user.type(el, "burger") | Clicks the field, then types one key at a time |
await user.type(el, "burger{Enter}") | Types, then presses Enter (submits the form) |
await user.clear(el) | Empties an input |
await user.keyboard("{Escape}") | Presses keys on whatever is focused |
await user.tab() | Moves focus, like the Tab key |
await user.selectOptions(select, "veg") | Picks an <option> |
await user.hover(el) | Pointer moves over it (for tooltips) |
fireEvent vs user-event
import { fireEvent } from "@testing-library/react";
fireEvent.change(input, { target: { value: "burger" } }); // value jumps in at once
fireEvent.click(searchButton); // one click event, nothing elseconst user = userEvent.setup();
await user.type(input, "burger"); // focus + keydown/keypress/input/keyup per letter
await user.click(searchButton); // pointer, mouse, focus and click eventsfireEvent still works and is occasionally useful for an event user-event doesn't model (like scroll). For anything a user does with a mouse or keyboard, use user-event.
Gotchas
Recall
Can you answer these?
0/3
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
