Sub topic 8
Simulating clicks and typing with user-event
This chapter assumes you can write React function components with state, you know async/await, and you have a Jest or Vitest project with @testing-library/jest-dom configured. It also assumes you know how to render a component and query it by role, as covered in earlier chapters.
Why user-event instead of fireEvent
@testing-library/react re-exports fireEvent. It dispatches a single DOM event, such as click, and does nothing else. A real click is more than that. The pointer moves over the element, the mouse button goes down and up, focus changes, and only then does the click event fire.
@testing-library/user-event is a separate package. It simulates the whole sequence the browser would produce. Typing a word fires keydown, keypress, input, and keyup for each character, and the element keeps focus throughout. Your component sees the same events it would see in a real browser.
Install it as a dev dependency:
npm install --save-dev @testing-library/user-eventThe setup pattern
Call userEvent.setup() once per test, before you render. It returns a user object that holds the state of the simulated keyboard and pointer. Every method on it returns a promise, so you must await each call.
// Counter.jsx
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
</div>
);
}
// Counter.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event'; './Counter';
test('increments the count when the button is clicked', async () => {
const user = userEvent.setup();
render(<Counter />);
expect(screen.get')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});The test function is async because of the await. Theessible name, so the test breaks only if the user-visible behavior changes.
Common interactions
The methods you will use most are listed below.
| Method | What it does |
|---|---|
| `user.click(element)` | Hovers, presses, and releases the primary mouse button |
| `user.dblClick(element)` | Two clicks in a row |
| `user.hover(element)` / `user.unhover(element)` | Moves the pointer onto or off an element |
| `user.type(element, text)` | Clicks the element, then types the text |
| `user.clear(element)` | Selects the content of an input and deletes it |
| `user.keyboard(text)` | Types into whatever currently has focus |
| `user.tab()` | Moves focus to the next focusable element |
| `user.selectOptions(select, values)` | Chooses options in a `<select>` |
user.type accepts special key sequences in braces. For example, {Enter} presses Enter and {Backspace} deletes a character. A literal { or [ must be doubled, as in {{.
await user.type(screen.getByLabelText('Email'), '[email protected]{Enter}');What user-event checks for you
user-event respects the state of the page, as a browser does. If a button is disabled, clicking it does nothing. If an element has pointer-events: none, user-event throws an error, because a real user could not click it. These checks catch tests that pass only because they bypass real interaction.
The flow below shows what user.click does internally.
Verifying the result
After an interaction, assert on what the user would see. Use the jest-dom matchers from earlier in the tutorial.
// LoginForm.jsx
import { useState } from 'react';
export function LoginForm({ onSubmit }) {
const [email, setEmail] = useState('');
return (
<form
onSubmit={(e) => {
e.preventDefault();
onSubmit({ email });
}}
>
<label htmlFor="email">Email</label>
<input id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit">Sign in</button>
</form>
);
}
// LoginForm.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LoginForm } from './LoginForm';
test('types into the field and keeps the typed value', async () => {
const user = userEvent.setup();
render(<LoginForm onSubmit={() => {}} />);
const input = screen.getByLabelText('Email');
await user.type(input, '[email protected]');
expect(input).toHaveValue('[email protected]');
});Common errors
- Forgetting
await. Without it, the assertion runs before the interaction finishes. The test fails with stale output, or passes by accident and then breaks later. - Calling
userEvent.click(...)directly with an old v13 habit. In v14 and later, callsetup()first and use the returneduser. - Wrapping calls in
act. user-event already wraps its work for React Testing Library. Addingactyourself is unnecessary. - Using
fireEventfor typing.fireEvent.changesets a value in one step and skips the keyboard events that youronKeyDownhandlers might depend on.
Exercise
A test calls user.click(screen.getByRole('button', { name: 'Save' })) without await, and the next line asserts that "Saved" appears. Why can this fail, and how do you fix it?
Show answer
Every user-event method returns a promise. Without await, the assertion runs before the simulated click has finished, so the "Saved" text is not on the page yet. Add await before user.click(...) and make sure the test function is declared async.
Exercise
A LoginForm input is found with screen.getByLabelText('Email'). Write the single user-event call that types [email protected] into it and presses Enter.
Show answer
await user.type(screen.getByLabelText('Email'), '[email protected]{Enter}');