Skip to content
ClapelloNotes by Barath
ReactCh 13 · 5/6
Core4 min readUpdated

React / 74

Simulating clicks and typing with user-event

TL;DR

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 it

fireEvent.click(button) fires

click

and nothing else: no focus, no pointer events

your real click fired

Click (or tap) “Add Masala Dosa”.

A real click is a whole sequence of events. user.click() replays that sequence; fireEvent.click() fires only the last one. (Safari doesn't focus buttons on click, so focus may be missing there.)

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

src/components/DishSearch.jsx
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

src/components/DishSearch.test.jsx
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();
});
  1. Set up a user

    userEvent.setup() first, before render. It returns a user that remembers things like which element is focused.
  2. Find, then act

    Find the element with a query, then await user.type(...) or await user.click(...).
  3. Assert what the user would see

    Check the list, not the results state.

The test function is async, and every user action is awaited: user-event fires its events asynchronously.

The actions you'll use

CallDoes
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 else
const user = userEvent.setup();
 
await user.type(input, "burger");  // focus + keydown/keypress/input/keyup per letter
await user.click(searchButton);    // pointer, mouse, focus and click events

fireEvent 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.