Testing User Interactions in React
Testing user interactions is an important part of React application development. It verifies that components respond correctly when users click buttons, type into input fields, submit forms, select options, check checkboxes, navigate using the keyboard, and perform other actions. These tests help developers confirm that the application behaves as expected from the user's perspective.
In React, user interactions can be tested using Vitest as the test runner, React Testing Library to render and inspect components, and the @testing-library/user-event package to simulate realistic user actions.
1. What Is Testing User Interactions?
Testing user interactions means checking how a React component behaves when a user performs an action. Instead of testing only whether a component renders, interaction tests verify whether the interface responds correctly to clicks, typing, selections, form submissions, and keyboard events.
For example, if a user clicks an Increment button, the displayed counter should increase. If a user submits a form with an invalid email address, an appropriate validation message should appear.
Examples of user interactions
- Clicking a button to update a counter.
- Typing text into an input field.
- Submitting a registration or login form.
- Selecting an option from a dropdown.
- Checking or unchecking a checkbox.
- Opening or closing a modal dialog.
- Adding or removing items from a list.
- Using keyboard keys to navigate or activate controls.
- Displaying validation messages after incorrect input.
2. Why Is Interaction Testing Important?
- Verifies functionality: Confirms that buttons, inputs, forms, and other controls work correctly.
- Detects bugs: Identifies problems in event handlers, state updates, and conditional rendering.
- Improves user experience: Checks that the application responds correctly to user actions.
- Protects against regressions: Helps ensure that new code changes do not break existing functionality.
- Tests validation: Confirms that incorrect or missing information is handled appropriately.
- Supports accessibility: Encourages testing controls through accessible roles, labels, and keyboard interactions.
- Improves maintainability: Makes it easier to change components with confidence.
3. Tools Required for Testing User Interactions
| Tool |
Purpose |
| Vitest |
Runs test cases and provides assertions, mocking, and watch mode. |
| React Testing Library |
Renders React components and provides utilities to inspect the rendered interface. |
| user-event |
Simulates interactions such as clicking, typing, selecting, and keyboard input. |
| jest-dom |
Adds DOM assertions such as toBeInTheDocument(), toBeVisible(), and toBeDisabled(). |
| jsdom |
Provides a simulated DOM environment for running component tests in Node.js. |
4. Installing the Required Packages
For an existing Vite-based React project, install the following development dependencies:
npm install -D vitest jsdom
npm install -D @testing-library/react @testing-library/user-event @testing-library/jest-dom
These packages provide the test runner, browser-like DOM environment, component rendering utilities, interaction simulation, and DOM assertions.
5. Configuring Vitest for React
Update your vite.config.js file to configure Vitest to use the jsdom environment for component tests.
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: './src/test/setup.js',
globals: true
}
});
The environment: 'jsdom' setting allows component tests to use DOM APIs. The setupFiles option loads shared test configuration before individual tests run. If you do not enable globals, import test functions such as describe, test, and expect from vitest.
Create the test setup file
Create src/test/setup.js and add:
import '@testing-library/jest-dom/vitest';
This enables additional DOM matchers in Vitest tests.
6. Adding Test Scripts
Add or update the scripts in your package.json:
{
"scripts": {
"dev": "vite",
"build": "vite build",
"test": "vitest",
"test:run": "vitest run"
}
}
Run npm run test to start Vitest in watch mode. Run npm run test:run to execute tests once and exit.
7. Understanding the Testing Process
Most interaction tests follow three basic steps: Arrange, Act, and Assert.
- Arrange: Render the React component and prepare the test environment.
- Act: Perform the user interaction, such as clicking a button or typing into a field.
- Assert: Verify that the expected result appears in the interface.
Example workflow
render(<Counter />);
await user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
This example renders a counter, clicks its Increment button, and verifies that the displayed count changes to one.
8. Testing Button Clicks
Buttons are common interactive elements in React applications. An interaction test should verify both that the button can be activated and that the expected behavior occurs.
Example component: Counter.jsx
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<section>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</section>
);
}
Test file: Counter.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import Counter from './Counter';
test('increments the count when clicked', async () => {
const user = userEvent.setup();
render(<Counter />);
await user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
Explanation: The test renders the component, finds the button by its accessible role and name, clicks it, and checks that React updates the displayed count.
9. Testing Text Input and Typing
Input testing verifies that a component correctly handles the text entered by a user. This is useful for search boxes, login forms, registration forms, comments, and profile settings.
Example component: Greeting.jsx
import { useState } from 'react';
export default function Greeting() {
const [name, setName] = useState('');
return (
<section>
<label htmlFor="username">Your name</label>
<input
id="username"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<p>Hello, {name || 'Guest'}!</p>
</section>
);
}
Test file: Greeting.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import Greeting from './Greeting';
test('updates the greeting when a name is entered', async () => {
const user = userEvent.setup();
render(<Greeting />);
await user.type(screen.getByRole('textbox', { name: 'Your name' }), 'Asha');
expect(screen.getByText('Hello, Asha!')).toBeInTheDocument();
});
Explanation: The test types a name into the textbox and checks whether the greeting reflects the entered value.
10. Testing Form Submission
Form interaction tests verify that the application processes submitted data correctly. Common checks include entering values, submitting the form, preventing unwanted page reloads, and displaying confirmation messages.
Example component: ContactForm.jsx
import { useState } from 'react';
export default function ContactForm() {
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
function handleSubmit(event) {
event.preventDefault();
if (!email.trim()) {
setMessage('Email is required');
return;
}
setMessage('Form submitted successfully');
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<button type="submit">Submit</button>
{message && <p role="status">{message}</p>}
</form>
);
}
Test file: ContactForm.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import ContactForm from './ContactForm';
test('shows an error when email is empty', async () => {
const user = userEvent.setup();
render(<ContactForm />);
await user.click(screen.getByRole('button', { name: 'Submit' }));
expect(screen.getByRole('status')).toHaveTextContent('Email is required');
});
test('shows success after entering an email', async () => {
const user = userEvent.setup();
render(<ContactForm />);
await user.type(screen.getByRole('textbox', { name: 'Email' }), '[email protected]');
await user.click(screen.getByRole('button', { name: 'Submit' }));
expect(screen.getByRole('status')).toHaveTextContent('Form submitted successfully');
});
Explanation: The first test checks the empty-email scenario. The second enters an email address, submits the form, and verifies the success message. This example demonstrates interaction handling, not complete email verification or a real backend submission.
11. Testing Checkboxes
Checkbox testing ensures that a checkbox changes its checked state when a user interacts with it. This is useful for terms and conditions, notification preferences, and settings.
Example component: TermsCheckbox.jsx
export default function TermsCheckbox() {
return (
<div>
<label>
<input type="checkbox" name="terms" />
Accept terms and conditions
</label>
</div>
);
}
Test file: TermsCheckbox.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import TermsCheckbox from './TermsCheckbox';
test('checks and unchecks the terms checkbox', async () => {
const user = userEvent.setup();
render(<TermsCheckbox />);
const checkbox = screen.getByRole('checkbox', {
name: 'Accept terms and conditions'
});
expect(checkbox).not.toBeChecked();
await user.click(checkbox);
expect(checkbox).toBeChecked();
await user.click(checkbox);
expect(checkbox).not.toBeChecked();
});
Explanation: The test checks the initial state, clicks the checkbox, verifies that it becomes checked, and clicks again to confirm that it becomes unchecked.
12. Testing Dropdown Selections
Dropdown tests verify that selecting an option updates the selected value or triggers the expected component behavior.
Example component: CourseSelect.jsx
import { useState } from 'react';
export default function CourseSelect() {
const [course, setCourse] = useState('');
return (
<div>
<label htmlFor="course">Choose a course</label>
<select
id="course"
value={course}
onChange={(event) => setCourse(event.target.value)}
>
<option value="">Select a course</option>
<option value="react">React JS</option>
<option value="flutter">Flutter</option>
</select>
<p>Selected course: {course || 'None'}</p>
</div>
);
}
Test file: CourseSelect.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import CourseSelect from './CourseSelect';
test('updates the selected course', async () => {
const user = userEvent.setup();
render(<CourseSelect />);
await user.selectOptions(
screen.getByRole('combobox', { name: 'Choose a course' }),
'react'
);
expect(screen.getByText('Selected course: react')).toBeInTheDocument();
});
Explanation: The test selects the React JS option and verifies that the component displays the selected value.
13. Testing Keyboard Interactions
Keyboard interaction tests check whether users can interact with the interface using keys such as Enter, Escape, Tab, and arrow keys. This is particularly important for accessibility and for users who do not use a mouse.
Example component: KeyboardAction.jsx
import { useState } from 'react';
export default function KeyboardAction() {
const [message, setMessage] = useState('Waiting for Enter');
return (
<div>
<label htmlFor="keyboard-input">Press Enter</label>
<input
id="keyboard-input"
onKeyDown={(event) => {
if (event.key === 'Enter') {
setMessage('Enter key pressed');
}
}}
/>
<p>{message}</p>
</div>
);
}
Test file: KeyboardAction.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import KeyboardAction from './KeyboardAction';
test('responds when Enter is pressed', async () => {
const user = userEvent.setup();
render(<KeyboardAction />);
const input = screen.getByRole('textbox', { name: 'Press Enter' });
await user.click(input);
await user.keyboard('{Enter}');
expect(screen.getByText('Enter key pressed')).toBeInTheDocument();
});
Explanation: The test focuses the input, simulates pressing Enter, and verifies that the expected message appears.
14. Testing Disabled Buttons
A disabled button should not be available for normal user activation. Tests can verify that the disabled state is correctly applied when a form is incomplete or an operation is in progress.
Example component: SaveButton.jsx
export default function SaveButton({ isSaving }) {
return (
<button disabled={isSaving}>
{isSaving ? 'Saving...' : 'Save'}
</button>
);
}
Test file: SaveButton.test.jsx
import { render, screen } from '@testing-library/react';
import { expect, test } from 'vitest';
import SaveButton from './SaveButton';
test('disables the button while saving', () => {
render(<SaveButton isSaving={true} />);
expect(screen.getByRole('button', { name: 'Saving...' })).toBeDisabled();
});
Explanation: The test verifies that the button is disabled while the component is in the saving state.
15. Testing Modal Open and Close Interactions
A modal is a dialog that appears above the main interface. Tests should verify that it opens when requested and closes when the appropriate control is activated.
Example component: ModalExample.jsx
import { useState } from 'react';
export default function ModalExample() {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(true)}>Open dialog</button>
{open && (
<section role="dialog" aria-labelledby="dialog-title">
<h2 id="dialog-title">Confirmation</h2>
<p>Do you want to continue?</p>
<button onClick={() => setOpen(false)}>Close dialog</button>
</section>
)}
</div>
);
}
Test file: ModalExample.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import ModalExample from './ModalExample';
test('opens and closes the dialog', async () => {
const user = userEvent.setup();
render(<ModalExample />);
await user.click(screen.getByRole('button', { name: 'Open dialog' }));
expect(screen.getByRole('dialog')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Close dialog' }));
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
Explanation: The test checks that the dialog appears after opening and is removed from the document after closing.
16. Testing Asynchronous User Interactions
Some interactions trigger asynchronous work, such as fetching data, submitting a request, or loading search results. In these cases, use asynchronous queries such as findByRole() or findByText() to wait for the expected element to appear.
Example test pattern
await user.click(screen.getByRole('button', { name: 'Load data' }));
const result = await screen.findByText('Data loaded successfully');
expect(result).toBeInTheDocument();
Explanation: The test clicks the Load data button and waits for the success message to appear. This pattern is useful when the component updates after an asynchronous operation.
For network-dependent components, use a controlled mock response or a request-mocking tool so that the test is predictable and does not depend on a real external service.
17. Testing User Interactions with fireEvent and user-event
React Testing Library provides fireEvent, while @testing-library/user-event provides a higher-level way to simulate user interactions.
| Feature |
fireEvent |
user-event |
| Purpose |
Dispatches a specific DOM event. |
Simulates a broader user interaction. |
| Typing |
Typically dispatches an input or change event directly. |
Simulates typing, including relevant focus and keyboard behavior. |
| Clicking |
Dispatches a click event. |
Simulates a click interaction with additional browser-like checks. |
| Usage |
Useful for low-level events or cases not supported by user-event. |
Recommended for most common user interactions. |
Example using fireEvent
import { fireEvent, render, screen } from '@testing-library/react';
import { expect, test } from 'vitest';
import Counter from './Counter';
test('increments using fireEvent', () => {
render(<Counter />);
fireEvent.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
Example using user-event
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import Counter from './Counter';
test('increments using user-event', async () => {
const user = userEvent.setup();
render(<Counter />);
await user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
For most everyday interactions, prefer user-event because it better represents how people use an interface. Use fireEvent when you need to dispatch a particular event that is not adequately represented by the higher-level interaction APIs.
18. Choosing the Correct Query
Testing Library provides different query methods to locate elements. Selecting the correct query makes tests more reliable and readable.
| Query |
Behavior |
Typical use |
getByRole() |
Returns a matching element or throws if none is found. |
Finding a button, heading, checkbox, or textbox. |
getByLabelText() |
Finds a form control through its label. |
Finding an input associated with a label. |
getByText() |
Finds an element by visible text. |
Checking a message or paragraph. |
queryByRole() |
Returns a matching element or null. |
Verifying that a dialog or message is absent. |
findByRole() |
Returns a promise and waits for an element to appear. |
Checking asynchronously displayed content. |
Prefer accessible queries such as getByRole() and getByLabelText() whenever possible. These queries help tests reflect how users and assistive technologies identify controls.
19. Common Mistakes in Interaction Testing
| Mistake |
Solution |
| Forgetting to await an interaction |
Use await user.click(), await user.type(), and other asynchronous user-event methods. |
| Using an incorrect accessible name |
Check the component's label, visible text, and accessible role. |
| Testing implementation details only |
Verify visible results and user-observable behavior. |
| Using getBy queries for content that appears later |
Use findBy... queries for asynchronous content. |
| Checking only the initial render |
Perform an interaction and assert the resulting UI change. |
| Ignoring invalid input |
Test empty values, incorrect formats, and other important edge cases. |
| Relying on real network services |
Use controlled mocks or request interception for predictable tests. |
| Ignoring accessibility |
Test semantic roles, accessible labels, and keyboard behavior where relevant. |
20. Best Practices for Testing User Interactions
- Write tests from the user's perspective.
- Use
userEvent.setup() inside each test before rendering the component.
- Await asynchronous user-event actions.
- Prefer accessible queries such as
getByRole() and getByLabelText().
- Check both the initial state and the result of the interaction.
- Test successful actions and invalid or unsuccessful cases.
- Use
findBy... queries when waiting for asynchronous content.
- Keep tests independent and avoid sharing mutable state between cases.
- Use mock functions to verify callback behavior when necessary.
- Test keyboard interactions for controls where keyboard access matters.
- Do not depend on internal React state or component implementation details when visible behavior is sufficient.
- Run the test suite whenever interaction-related code changes.
21. Mini Project: Testing a To-Do List
Create a simple To-Do list that allows users to enter tasks and add them to a list. Then test whether typing and clicking work correctly.
Component: TodoList.jsx
import { useState } from 'react';
export default function TodoList() {
const [task, setTask] = useState('');
const [tasks, setTasks] = useState([]);
function handleSubmit(event) {
event.preventDefault();
const value = task.trim();
if (!value) return;
setTasks((current) => [...current, value]);
setTask('');
}
return (
<section>
<h2>My Tasks</h2>
<form onSubmit={handleSubmit}>
<label htmlFor="task">Task name</label>
<input
id="task"
value={task}
onChange={(event) => setTask(event.target.value)}
/>
<button type="submit">Add Task</button>
</form>
<ul>
{tasks.map((item, index) => (
<li key={`${item}-${index}`}>{item}</li>
))}
</ul>
</section>
);
}
Test: TodoList.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import TodoList from './TodoList';
test('adds a task when the form is submitted', async () => {
const user = userEvent.setup();
render(<TodoList />);
await user.type(screen.getByRole('textbox', { name: 'Task name' }), 'Learn React');
await user.click(screen.getByRole('button', { name: 'Add Task' }));
expect(screen.getByRole('listitem')).toHaveTextContent('Learn React');
});
test('does not add an empty task', async () => {
const user = userEvent.setup();
render(<TodoList />);
await user.click(screen.getByRole('button', { name: 'Add Task' }));
expect(screen.queryByRole('listitem')).not.toBeInTheDocument();
});
This mini project tests text entry, button clicks, form submission, list rendering, and empty-input handling.
22. Interview Questions and Answers
Q1. What is user interaction testing in React?
It is the process of testing how React components respond to actions such as clicks, typing, form submissions, selections, and keyboard input.
Q2. Which tools are commonly used for testing React interactions?
Vitest or another test runner, React Testing Library, and @testing-library/user-event are commonly used together.
Q3. What is the purpose of user-event?
It simulates common user actions with browser-like behavior so that tests can verify how the interface responds to realistic interactions.
Q4. What is the difference between fireEvent and user-event?
fireEvent dispatches a specific DOM event, while user-event simulates a higher-level interaction that may involve multiple events and additional checks.
Q5. Why should user-event methods be awaited?
Many user-event methods return promises. Awaiting them ensures the simulated interaction completes before the test checks the result.
Q6. How do you test a button click?
Render the component, locate the button using an accessible query, click it using user-event, and assert the expected result.
Q7. How do you test a checkbox?
Locate the checkbox by its role and accessible name, interact with it, and use assertions such as toBeChecked() and not.toBeChecked().
Q8. How do you test asynchronous UI updates?
Perform the interaction and use an asynchronous query such as findByText() or findByRole() to wait for the expected content.
Q9. Why are accessible queries important?
They make tests more closely reflect how users identify controls and help encourage accessible component design.
Q10. What should interaction tests verify?
They should verify the visible and functional result of an action, including successful behavior, validation, disabled states, and relevant error cases.
23. Practice Exercises
- Create a counter with Increment and Decrement buttons and test both actions.
- Create a search field and test that typing updates the search result.
- Create a login form and test empty-field validation.
- Create a checkbox for accepting terms and test both checked states.
- Create a dropdown with three options and test selecting each option.
- Create a modal dialog and test opening and closing it.
- Create a form with a submit button and test the success message.
- Create a component that responds to the Enter key and test keyboard interaction.
- Create a button that becomes disabled during loading and test its state.
- Extend the To-Do project to support deleting tasks and test the delete interaction.
24. Revision Checklist
- Understand the meaning and importance of user interaction testing.
- Install Vitest, jsdom, React Testing Library, user-event, and jest-dom.
- Configure the test environment and setup file.
- Use the Arrange, Act, and Assert testing pattern.
- Test clicks, text input, forms, checkboxes, dropdowns, and keyboard actions.
- Understand when to use
fireEvent and user-event.
- Use accessible queries to locate interactive elements.
- Await interactions and asynchronous UI updates correctly.
- Test both successful and invalid user actions.
- Practice writing component interaction tests with Vitest.
25. Official Learning Resources
26. Learn React JS with JustAcademy
Learn React components, props, state, hooks, event handling, testing, and practical application development to strengthen your frontend development skills.
JustAcademy React JS Training Course
Explore the training course and build your understanding of React through structured learning and practical exercises.
Register for React JS Course Demo
Conclusion
Testing user interactions helps verify that React applications behave correctly when people click, type, select, submit forms, and use the keyboard. By combining Vitest, React Testing Library, and user-event, developers can create reliable tests that focus on visible outcomes and realistic user behavior. Practicing these techniques helps improve application quality, accessibility, and maintainability.