Hello! Welcome to the next lesson in our module on Testing, Building, and Deploying.
In our previous lesson, we explored integration testing, learning how to verify that components with state, props, and context work together as expected. We had a brief introduction to the @testing-library/user-event library to simulate clicks. Today, we're going to take a deep dive into that library.
This lesson is dedicated to mastering how to simulate user interactions like clicks and input typing using @testing-library/user-event. You will learn why this library is the industry standard for interaction testing and how to use its powerful API to create realistic, user-centric tests for the most interactive parts of your application.
1. The Philosophy of user-event: Simulating Behavior, Not Events
Before we write code, it's important to understand the conceptual difference between @testing-library/user-event and the lower-level fireEvent API that also comes with React Testing Library. Your background in software engineering will help you appreciate this distinction in tool design.
fireEvent is a lightweight wrapper that dispatches a single, specific DOM event. For example, fireEvent.click(button) dispatches a click event and nothing more.
@testing-library/user-event, on the other hand, simulates a full user interaction. A single call to a user-event method often dispatches a whole sequence of events, just as a real user would trigger. For example, user.click(button) might dispatch pointerOver, pointerEnter, mouseOver, mouseEnter, pointerDown, mouseDown, focus the button, pointerUp, mouseUp, and finally, click. This high-fidelity simulation makes your tests more robust and more likely to catch bugs that fireEvent would miss.
To solidify this crucial concept, please read the official documentation. It clearly explains the difference between simulating full interactions and dispatching single events.
Please read the section titled 'Differences from fireEvent'. Focus on the example of what happens when a user types into a textbox—it's not just one event, but a series of them, which user-event aims to replicate.
2. The Modern user-event API: setup, click, and type
As the documentation mentions, the recommended way to use user-event is to create a new instance for each test using userEvent.setup(). This ensures test isolation and provides a clean, consistent API.
The pattern looks like this:
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MyComponent from './MyComponent';
test('should do something when user interacts', async () => {
// 1. Set up the user-event instance
const user = userEvent.setup();
// 2. Render the component (Arrange)
render(<MyComponent />);
// 3. Find elements and interact (Act)
const button = screen.getByRole('button');
await user.click(button);
// 4. Assert the result
// ... assertions
});
Notice the use of async/await. All user-event APIs return promises, reflecting the fact that user interactions are not instantaneous. They may involve built-in delays (e.g., for type) or trigger asynchronous updates in your component. Always await them.
Simulating Clicks
Let's revisit the TermsAndConditions checkbox example. It's a perfect demonstration of using user.click() to trigger a state change and then asserting the resulting UI update.
React Testing for Beginners: Start Here!
This clip from Programming with Mosh's course clearly demonstrates the Arrange-Act-Assert pattern for an interaction test. It covers setting up user-event, simulating a click, and asserting the outcome.
Please watch from 58:48 to 01:02:24. Pay close attention to how userEvent.setup() is called, how await user.click(checkbox) simulates the action, and how the final assertion, expect(button).toBeEnabled(), confirms the component's behavior.
Simulating Typing
Typing into form fields is another fundamental user interaction. user-event provides the type API for this. It simulates a user focusing an input and typing characters one by one.
// Arrange: Find the input
const nameInput = screen.getByRole('textbox', { name: /name/i });
// Act: Simulate typing
await user.type(nameInput, 'Satoshi');
// Assert: Check the input's value
expect(nameInput).toHaveValue('Satoshi');
You can also use user.clear(element) to simulate clearing an input field before typing something new.
For a quick reference on these APIs, the following article provides concise code snippets.
Introduction to Testing in React with TypeScript
This section of an article from dev.to serves as a handy cheatsheet for the most common user-event interactions.
Quickly review the User Interactions section. Notice the examples for userEvent.click and userEvent.type. This reinforces what we've just discussed.
3. A Complex Interaction Walkthrough: The ExpandableText Component
Now, let's put our knowledge to the test with a more complex, multi-step interaction. We will analyze the tests for an ExpandableText component. This component truncates long text and provides a "Show More" button. Clicking it expands the text and changes the button to "Show Less". A subsequent click collapses it again.
This scenario requires us to:
- Test the initial (truncated) state.
- Simulate a click and assert that the text expands and the button label changes.
- Simulate a second click and assert that the text collapses and the button label reverts.
This is a fantastic, real-world example of building a test that follows a complete user journey.
React Testing for Beginners: Start Here!
This extended segment from Programming with Mosh provides a masterclass in testing a component with sequential user interactions. He meticulously builds up the tests for the ExpandableText component.
Please watch from 01:02:24 to 01:13:21. This is the core practical part of our lesson. Follow along as he: Writes rendering tests for short and long text. Writes the first interaction test: clicking 'Show More' and asserting the text expands. Writes the second interaction test: clicking 'Show Less' and asserting the text collapses. Notice how he structures the tests and refactors the code for clarity, like renaming variables to showMoreButton and showLessButton.
Test your understanding!
Consider a simple login form with an email input, a password input, and a "Login" button. The button has an onSubmit prop that is a function. Write down the Arrange-Act-Assert steps to test a successful submission.
Show answer
-
Arrange:
- Create a mock function for the submit handler:
const handleSubmit = vi.fn(); - Render the form, passing the mock function:
render(<LoginForm onSubmit={handleSubmit} />); - Query the email input, password input, and the login button.
- Create a mock function for the submit handler:
-
Act:
- Set up user-event:
const user = userEvent.setup(); - Simulate typing into the email input:
await user.type(emailInput, 'test@example.com'); - Simulate typing into the password input:
await user.type(passwordInput, 'password123'); - Simulate clicking the login button:
await user.click(loginButton);
- Set up user-event:
-
Assert:
- Verify that the
handleSubmitmock function was called.expect(handleSubmit).toHaveBeenCalled(); - (Optional but recommended) Verify it was called with the correct data:
expect(handleSubmit).toHaveBeenCalledWith({ email: 'test@example.com', password: 'password123' });
- Verify that the
4. Other Useful Interactions
@testing-library/user-event can simulate much more than just clicks and typing. Here are a few other useful APIs for your toolbox:
- Pointer Interactions:
user.dblClick(element),user.hover(element),user.unhover(element). These are great for testing tooltips, context menus, or drag-and-drop interfaces. - Keyboard Interactions: You can simulate pressing special keys by passing strings in curly braces to
user.type(). For example,await user.type(input, '{enter}')simulates pressing the Enter key, which is perfect for testing form submissions via the keyboard.user.tab()simulates pressing the Tab key, which is essential for testing accessibility and focus management.
Introduction to Testing in React with TypeScript
The same dev.to article provides quick examples for these advanced interactions. It's a good idea to be aware of them for future use.
Scan through the Pointer Interactions and Keyboard Interactions sections to see the syntax for these actions. You don't need to memorize them, just be aware they exist.
Conclusion
You have now completed a deep dive into @testing-library/user-event. By simulating user behavior with high fidelity, you can write tests that provide strong confidence in your component's functionality, from simple state toggles to complex, multi-step user flows.
Key Takeaways:
user-eventoverfireEvent: Always preferuser-eventbecause it simulates full user interactions, not just single events, leading to more realistic and robust tests.- The
userEvent.setup()Pattern: Start every interaction test by creating an isolateduser-eventinstance withconst user = userEvent.setup();. - Interactions are
async: Alwaysawaitcalls touser.click(),user.type(), and otheruser-eventAPIs. - Simulate Clicks and Typing: The
clickandtypemethods are your workhorses for testing most interactive components. - Test the Full Flow: For complex components, write tests that simulate a complete user journey, including multiple interactions and assertions, to verify the component behaves correctly at every step.
Preview of the Next Lesson:
So far, our tests have focused on the "happy path"—what happens when things go right. But what happens when things go wrong? In the next lesson, we will learn how to implement Error Boundaries using a class component to catch and handle runtime errors gracefully, a crucial pattern for building resilient applications.