Sub topic 8
Simulating clicks and typing with user-event
This chapter assumes you can already render a component, query elements with screen, and assert with jest-dom matchers. It also assumes you are comfortable with async/await. By the end you will be able to drive a component with realistic clicks, typing, keyboard navigation, and selection, and to avoid the usual mistakes.
Why user-event instead of fireEvent
@testing-library/react re-exports fireEvent, which dispatches a single DOM event. fireEvent.click(button) fires one click and nothing else.
A real click is a sequence. The pointer moves over the element, the mouse button goes down, focus moves, the button goes up, and then click fires. Typing is similar. Each character produces keydown, keypress, beforeinput, input, and keyup, and the input's value changes between them.
@testing-library/user-event reproduces these sequences. It also respects browser rules, such as skipping clicks on disabled elements and moving focus when you click. Your test then exercises the same code paths a user triggers.
| Aspect | `fireEvent` | `user-event` |
|---|---|---|
| Events per action | One | The full realistic sequence |
| Focus handling | None | Moves focus like a browser |
| Disabled elements | Handlers may still run | Ignored, as in a browser |
| Typing | Set a value, fire `change` | One keystroke at a time |
| API style | Synchronous | Returns promises |
Use fireEvent only for events that user-event cannot model, such as a custom event or a low-level scroll.
Setting up user-event
This chapter uses the current API (v14). Call userEvent.setup() before you render, and use the returned object for every interaction.
// 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';
import { Counter } from './Counter';
test('increments the count when the 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();
});setup() creates an instance that tracks statels: which keys are held down, where the pointer is, and what the clipboard holds. Without setup(), that state would not carry from one call to the next. Calling it also lets you pass options (covered below).
Every call is asynchronous
All user-event methods return promises. Forgetting await is the most common mistake. The test continues before the interaction finishes, so your assertion runs against stale output. It may even pass or fail at random.
// Wrong: the assertion can run before the click is processed
user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
// Right
await user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();The test function must be async for this to work. A lint rule such as testing-library/await-async-events catches missing awaits.
Clicking and pointer actions
These are the pointer methods you will use most often.
user.click(element)performs a left click.user.dblClick(element)performs a double click.user.tripleClick(element)performs a triple click, which selects a line of text.user.hover(element)anduser.unhover(element)move the pointer on and off an element. Use them for tooltips and menus that open on hover.user.pointer(...)gives low-level control, such as a right click or a press-and-hold.
Clicking an element that a real user could not click does nothing. A button with the disabled attribute is skipped, and so is an element with CSS pointer-events: none. In the second case, user-event throws an error instead of silently continuing.
// SaveButton.jsx
export function SaveButton({ onSave, disabled }) {
return (
<button onClick={onSave} disabled={disabled}>
Save
</button>
);
}
// SaveButton.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SaveButton } from './SaveButton';
test('does not call onSave when disabled', async () => {
const user = userEvent.setup();
const handleSave = jest.fn();
render(<SaveButton onSave={handleSave} disabled />);
const button = screen.getByRole('button', { name: 'Save' });
await user.click(button);
expect(button).toBeDisabled();
expect(handleSave).not.toHaveBeenCalled();
});Typing text
user.type(element, text) clicks the element first, then types each character. Each keystroke triggers the same onChange handler a user would trigger.
// 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('submits the entered email', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn();
render(<LoginForm onSubmit={handleSubmit} />);
await user.type(screen.getByLabelText('Email'), '[email protected]');
await user.click(screen.getByRole('button', { name: 'Sign in' }));
expect(handleSubmit).toHaveBeenCalledWith({ email: '[email protected]' });
});Related methods:
user.clear(element)selects the field's contents and deletes them. It works on inputs and textareas.user.paste(text)pastes text into the focused element. This is faster thantypewhen you do not care about individual keystrokes.user.type(element, text, { initialSelectionStart, initialSelectionEnd })places the caret before typing.
If a field already contains text, type appends to it. Call clear first when you want to replace the value.
Special keys
Inside the string passed to type or keyboard, curly braces name special keys, and square brackets name physical keys by code.
| Syntax | Meaning |
|---|---|
| `{Enter}` | Press and release Enter |
| `{Backspace}` | Delete the previous character |
| `{Shift>}` | Press Shift and hold it |
| `{/Shift}` | Release Shift |
| `{Shift>}a{/Shift}` | Type `A` while holding Shift |
| `{{` | Type a literal `{` |
| `[[` | Type a literal `[` |
The literal forms matter for text that contains braces, such as JSON.
await user.type(screen.getByLabelText('Payload'), '{{"id": 1}');This types {"id": 1}. The first {{ becomes one literal brace. The closing brace needs no escaping.
Keyboard and focus
user.keyboard(text) sends keys to whatever element currently has focus. It does not click first. user.tab() moves focus the way the Tab key does, and user.tab({ shift: true }) moves it backward. Use these to test keyboard accessibility.
// SearchBox.jsx
import { useState } from 'react';
export function SearchBox({ onSearch }) {
const [query, setQuery] = useState('');
return (
<form
onSubmit={(e) => {
e.preventDefault();
onSearch(query);
}}
>
<label htmlFor="query">Search</label>
<input id="query" value={query} onChange={(e) => setQuery(e.target.value)} />
<button type="submit">Go</button>
</form>
);
}
// SearchBox.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SearchBox } from './SearchBox';
test('submits with the Enter key and supports tab order', async () => {
const user = userEvent.setup();
const handleSearch = jest.fn();
render(<SearchBox onSearch={handleSearch} />);
await user.tab();
expect(screen.getByLabelText('Search')).toHaveFocus();
await user.keyboard('react{Enter}');
expect(handleSearch).toHaveBeenCalledWith('react');
await user.tab();
expect(screen.getByRole('button', { name: 'Go' })).toHaveFocus();
});The first tab() lands on the input because it is the first focusable element. Typing then goes to the focused input, and Enter submits the form.
Selecting options and uploading files
For a native <select>, use selectOptions with a value or visible text. For a file input, use upload with a File object.
// Pickers.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
test('selects an option and uploads a file', async () => {
const user = userEvent.setup();
render(
<div>
<label htmlFor="color">Color</label>
<select id="color" defaultValue="">
<option value="">Choose</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
<label htmlFor="avatar">Avatar</label>
<input id="avatar" type="file" />
</div>
);
await user.selectOptions(screen.getByLabelText('Color'), 'blue');
expect(screen.getByLabelText('Color')).toHaveValue('blue');
const file = new File(['pixels'], 'me.png', { type: 'image/png' });
await user.upload(screen.getByLabelText('Avatar'), file);
expect(screen.getByLabelText('Avatar').files[0]).toBe(file);
});Options and fake timers
userEvent.setup() accepts options. The most useful are:
delay: milliseconds between actions. The default is0, which still yields to the event loop between steps. Setdelay: nullto skip waiting entirely.advanceTimers: a function user-event calls to advance fake timers while it waits.skipHover,pointerEventsCheck, andapplyAcceptfor finer control over pointer and upload behavior.
When a test uses Jest's fake timers, user-event's internal waits never finish unless you connect the two. A test that hangs until timeout is the usual symptom.
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
test('works with fake timers', async () => {
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
// render and interact as usual
});In Vitest, pass vi.advanceTimersByTime instead.
Common errors
- Missing
await. Assertions run before the interaction completes. Await every call. - Calling
setup()afterrender. Always call it first. A globaluserEvent.click(...)still works, but it creates a fresh instance each time, so state such as held keys is lost. - Using
user.typeto press a single key. Preferuser.keyboard('{Enter}')when the element already has focus, becausetypeclicks the element first and may change focus or selection. - Typing into the wrong element. Query the field by label or role. A wrapper
divcannot receive text. - Pointer-events errors. If user-event reports that the element has
pointer-events: none, check whether a CSS class or overlay blocks it. Do not disable the check just to make a test pass.
Exercise
A test calls user.type(screen.getByLabelText('Name'), 'Ada') on an input that already contains "Grace". What value does the input have afterward, and how do you make the test replace the old value?
Show answer
The input contains "GraceAda", because type appends to existing text. Call await user.clear(input) before typing, or select the text first. The test then ends with "Ada".
Exercise
Your test uses jest.useFakeTimers() and hangs until it times out on its first await user.click(...). What is the cause, and what is the fix?
Show answer
user-event waits between actions using timers, and fake timers never fire on their own. Create the instance with userEvent.setup({ advanceTimers: jest.advanceTimersByTime }) (or vi.advanceTimersByTime in Vitest) so user-event advances the fake clock itself.
Exercise
Write the user-event line that types Hello with a capital H into a focused input without using the capital letter directly, by holding Shift.
Show answer
await user.keyboard('{Shift>}h{/Shift}ello'); The {Shift>} syntax presses and holds Shift, {/Shift} releases it, and the remaining letters are typed in lowercase.