Testing Forms and Events in React
Testing forms and events in React is an important part of building reliable and user-friendly web applications. It helps developers verify that forms accept the correct input, validate data, respond to user actions, display error messages, and submit information correctly. React applications commonly use tools such as Vitest, Jest, React Testing Library, and user-event to test these behaviours.
Course: JustAcademy React JS Training Course
Course Demo: Register for React JS Course Demo
1. Introduction to Testing Forms and Events
Forms allow users to enter information, such as names, email addresses, passwords, contact details, and search queries. Events represent actions performed by users, such as clicking buttons, typing text, selecting options, or submitting a form.
Testing forms and events verifies that these interactions work as expected and that the application responds correctly.
Examples of Form Testing
- Checking whether a text field accepts user input.
- Verifying that required fields cannot be left empty.
- Checking whether invalid email addresses display an error.
- Confirming that valid form data is submitted.
- Verifying that a success message appears after submission.
Examples of Event Testing
- Testing button clicks.
- Testing input changes.
- Testing form submissions.
- Testing checkbox and radio button selections.
- Testing keyboard interactions.
- Verifying that event handlers update React state correctly.
2. What Is Form Testing?
Form testing is the process of checking whether a form behaves correctly when users enter, modify, validate, and submit information. In React, forms often use state to manage input values and event handlers to respond to user actions.
Common form elements include:
input — collects text, email addresses, passwords, numbers, and other values.
textarea — collects multi-line text.
select — allows users to choose an option.
checkbox — allows a user to select or deselect an option.
radio — allows a user to choose one option from a group.
button — performs an action, such as submitting a form.
3. What Are Events in React?
Events are actions or interactions that occur in the browser. React provides event handlers that allow components to respond to these interactions. React event handler names generally use camelCase.
| Event Handler |
Purpose |
Example |
onClick |
Responds to a click. |
Button click |
onChange |
Responds to changes in an input value or selection. |
Typing into a field |
onSubmit |
Responds to form submission. |
Submitting a registration form |
onBlur |
Responds when an element loses focus. |
Leaving an email field |
onFocus |
Responds when an element receives focus. |
Selecting a text field |
onKeyDown |
Responds when a key is pressed down. |
Pressing Enter |
onKeyUp |
Responds when a key is released. |
Releasing a key |
4. Tools Used for Testing Forms and Events
4.1 React Testing Library
React Testing Library helps developers test React components from the user's perspective. It encourages tests that interact with the interface rather than depending on internal implementation details.
4.2 user-event
The @testing-library/user-event package simulates user interactions such as typing, clicking, selecting options, and tabbing through fields. It is generally preferred for realistic user interaction tests.
4.3 Vitest
Vitest is a JavaScript testing framework that provides test functions, assertions, mocks, and test-running capabilities. It works well with Vite-based React applications.
4.4 Jest
Jest is another JavaScript testing framework commonly used in React projects. A project typically uses either Jest or Vitest as its test runner, depending on its configuration.
5. Installing Testing Dependencies
For a React project using Vite and Vitest, install the required packages with the following command:
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom
Configure Vitest to use the jsdom environment so that tests can work with a simulated browser DOM.
// vite.config.js
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: './src/test/setup.js'
}
});
Create a setup file to load additional DOM assertions:
// src/test/setup.js
import '@testing-library/jest-dom/vitest';
Add a test script to the project's package.json if one is not already configured:
{
"scripts": {
"test": "vitest",
"test:run": "vitest run"
}
}
Use the scripts supported by your existing project configuration. If the project uses Jest, follow its setup instructions instead of mixing test runners.
6. Creating a React Form Component
Before testing a form, create a component that accepts user input and handles submission. The following example uses controlled inputs, which means React state stores their values.
// RegistrationForm.jsx
import { useState } from 'react';
export default function RegistrationForm({ onRegister }) {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
function handleSubmit(event) {
event.preventDefault();
setError('');
setSuccess('');
if (!name.trim()) {
setError('Name is required');
return;
}
if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) {
setError('Enter a valid email address');
return;
}
onRegister({ name: name.trim(), email });
setSuccess('Registration successful');
}
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name</label>
<input
id="name"
value={name}
onChange={(event) => setName(event.target.value)}
required
/>
</div>
<div>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
required
/>
</div>
<button type="submit">Register</button>
{error && <p role="alert">{error}</p>}
{success && <p role="status">{success}</p>}
</form>
);
}
Important: In a real JSX source file, write normal JSX tags such as <form> directly. The escaped tags in the example above are shown to keep the code readable in an HTML document.
Understanding the Component
useState stores the name, email, error, and success message.
onChange updates the state when the user types.
onSubmit runs the submission handler.
preventDefault() prevents the browser's default form navigation.
- Validation checks that the name and email are valid according to the component's rules.
onRegister is called with the submitted data when validation succeeds.
role="alert" and role="status" make messages easier to identify in accessible interfaces and tests.
7. Writing the First Form Test
A form test usually renders the component, finds fields using accessible labels, performs user interactions, and checks the visible result.
// RegistrationForm.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi } from 'vitest';
import RegistrationForm from './RegistrationForm';
describe('RegistrationForm', () => {
it('renders the name and email fields', () => {
render(<RegistrationForm onRegister={() => {}} />);
expect(screen.getByLabelText(/name/i)).toBeInTheDocument();
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
expect(
screen.getByRole('button', { name: /register/i })
).toBeInTheDocument();
});
});
This test checks that the form renders the expected controls. Using labels and accessible roles makes tests more representative of how users interact with the page.
8. Testing Text Input Events
Text input testing verifies that users can type into fields and that the displayed field value updates correctly.
it('allows the user to enter a name', async () => {
const user = userEvent.setup();
render(<RegistrationForm onRegister={() => {}} />);
const nameInput = screen.getByLabelText(/name/i);
await user.type(nameInput, 'Aarav Sharma');
expect(nameInput).toHaveValue('Aarav Sharma');
});
The test uses user.type() to simulate typing. Because user-event interactions are asynchronous, use await when performing them.
9. Testing Form Submission
Form submission testing verifies that valid information reaches the expected callback and that the success message is displayed.
it('submits valid registration details', async () => {
const user = userEvent.setup();
const onRegister = vi.fn();
render(<RegistrationForm onRegister={onRegister} />);
await user.type(screen.getByLabelText(/name/i), 'Aarav Sharma');
await user.type(
screen.getByLabelText(/email/i),
'[email protected]'
);
await user.click(screen.getByRole('button', { name: /register/i }));
expect(onRegister).toHaveBeenCalledWith({
name: 'Aarav Sharma',
email: '[email protected]'
});
expect(screen.getByRole('status')).toHaveTextContent(
/registration successful/i
);
});
The mock function vi.fn() allows the test to verify whether the callback was called and what data it received.
10. Testing Validation Errors
Validation tests verify that invalid input does not get submitted and that appropriate feedback is displayed.
10.1 Testing an Invalid Email Address
it('shows an error for an invalid email address', async () => {
const user = userEvent.setup();
const onRegister = vi.fn();
render(<RegistrationForm onRegister={onRegister} />);
await user.type(screen.getByLabelText(/name/i), 'Aarav');
await user.type(screen.getByLabelText(/email/i), 'invalid-email');
await user.click(screen.getByRole('button', { name: /register/i }));
expect(await screen.findByRole('alert')).toHaveTextContent(
/enter a valid email address/i
);
expect(onRegister).not.toHaveBeenCalled();
});
Note that an input with type="email" may be blocked by native browser validation before the form's submit handler runs. If you want to test your custom validation message for an invalid email, consider using noValidate on the form or otherwise configuring the test to bypass native constraint validation. For example, add noValidate to the form element when custom validation is responsible for all validation feedback.
10.2 Testing a Required Name
If a field is required, test that the user cannot successfully submit the form without providing a value. Native browser validation and custom validation can behave differently, so test the approach your application actually uses.
it('does not register an empty name', async () => {
const user = userEvent.setup();
const onRegister = vi.fn();
render(<RegistrationForm onRegister={onRegister} />);
await user.type(screen.getByLabelText(/email/i), '[email protected]');
await user.click(screen.getByRole('button', { name: /register/i }));
expect(onRegister).not.toHaveBeenCalled();
});
11. Testing Button Click Events
Buttons frequently trigger actions such as clearing a form, opening a dialog, saving information, or showing a message. Test both the user's action and the resulting behaviour.
import { useState } from 'react';
function ToggleMessage() {
const [visible, setVisible] = useState(false);
return (
<div>
<button onClick={() => setVisible(!visible)}>
Toggle Message
</button>
{visible && <p>Hello, React!</p>}
</div>
);
}
it('shows a message when the button is clicked', async () => {
const user = userEvent.setup();
render(<ToggleMessage />);
await user.click(
screen.getByRole('button', { name: /toggle message/i })
);
expect(screen.getByText(/hello, react!/i)).toBeInTheDocument();
});
12. Testing Checkboxes
Checkbox tests verify whether an option can be selected and deselected and whether the component responds to the change.
it('allows the user to select a checkbox', async () => {
const user = userEvent.setup();
render(
<label>
<input type="checkbox" />
Accept terms
</label>
);
const checkbox = screen.getByRole('checkbox', {
name: /accept terms/i
});
await user.click(checkbox);
expect(checkbox).toBeChecked();
await user.click(checkbox);
expect(checkbox).not.toBeChecked();
});
13. Testing Radio Buttons
Radio buttons allow users to choose one option from a group. Testing should confirm that the selected option becomes checked and that selecting another option changes the selection.
it('allows the user to select a plan', async () => {
const user = userEvent.setup();
render(
<fieldset>
<legend>Choose a plan</legend>
<label>
<input type="radio" name="plan" value="basic" />
Basic
</label>
<label>
<input type="radio" name="plan" value="premium" />
Premium
</label>
</fieldset>
);
const basic = screen.getByRole('radio', { name: /basic/i });
const premium = screen.getByRole('radio', { name: /premium/i });
await user.click(premium);
expect(premium).toBeChecked();
expect(basic).not.toBeChecked();
});
14. Testing Dropdowns and Select Elements
Dropdown tests verify that the correct option can be selected and that the selected value updates as expected.
it('allows the user to select a country', async () => {
const user = userEvent.setup();
render(
<label>
Country
<select defaultValue="">
<option value="">Choose a country</option>
<option value="india">India</option>
<option value="canada">Canada</option>
</select>
</label>
);
const country = screen.getByRole('combobox', { name: /country/i });
await user.selectOptions(country, 'india');
expect(country).toHaveValue('india');
});
15. Testing Keyboard Events
Keyboard interaction tests help verify that users can operate a form without relying exclusively on a mouse. Examples include navigating between fields with Tab and submitting a form with Enter.
it('allows keyboard navigation between fields', async () => {
const user = userEvent.setup();
render(
<form>
<label>
Name
<input />
</label>
<label>
Email
<input type="email" />
</label>
<button type="submit">Submit</button>
</form>
);
const name = screen.getByLabelText(/name/i);
const email = screen.getByLabelText(/email/i);
await user.tab();
expect(name).toHaveFocus();
await user.tab();
expect(email).toHaveFocus();
});
Keyboard tests are especially useful for accessibility, forms, menus, dialogs, and interactive controls.
16. Testing Form Reset Behaviour
Some forms allow users to clear all entered information. Test whether resetting the form restores the expected initial values.
it('resets form fields', async () => {
const user = userEvent.setup();
render(
<form>
<label>
Name
<input defaultValue="" />
</label>
<button type="reset">Reset</button>
</form>
);
const name = screen.getByLabelText(/name/i);
await user.type(name, 'Aarav');
expect(name).toHaveValue('Aarav');
await user.click(screen.getByRole('button', { name: /reset/i }));
expect(name).toHaveValue('');
});
For controlled React inputs, resetting the DOM alone may not reset React state. Implement an explicit reset handler that updates the component state, then test that behaviour.
17. Testing Textarea Fields
A textarea collects multi-line text, such as comments, feedback, or descriptions. Tests can verify that users can enter and edit text.
it('allows the user to enter feedback', async () => {
const user = userEvent.setup();
render(
<label>
Feedback
<textarea />
</label>
);
const feedback = screen.getByRole('textbox', {
name: /feedback/i
});
await user.type(feedback, 'The course was helpful.');
expect(feedback).toHaveValue('The course was helpful.');
});
18. Testing Event Handlers with Mock Functions
Mock functions help verify whether callbacks are invoked, how many times they are invoked, and which arguments they receive.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, it, vi } from 'vitest';
function SaveButton({ onSave }) {
return (
<button onClick={() => onSave('Saved')}>
Save
</button>
);
}
it('calls the save handler with the expected value', async () => {
const user = userEvent.setup();
const onSave = vi.fn();
render(<SaveButton onSave={onSave} />);
await user.click(screen.getByRole('button', { name: /save/i }));
expect(onSave).toHaveBeenCalledTimes(1);
expect(onSave).toHaveBeenCalledWith('Saved');
});
Mock functions are useful when a component calls a parent callback, submits data to a service, or triggers another action that should be checked separately.
19. Testing Asynchronous Form Behaviour
Some forms display loading indicators, wait for a server response, and then show success or error messages. Asynchronous tests should wait for the relevant result rather than assuming it appears immediately.
import { useState } from 'react';
function ContactForm({ sendMessage }) {
const [status, setStatus] = useState('');
async function handleSubmit(event) {
event.preventDefault();
setStatus('Sending');
try {
await sendMessage();
setStatus('Message sent');
} catch {
setStatus('Unable to send message');
}
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Send Message</button>
{status === 'Sending' && <p role="status">Sending...</p>}
{status === 'Message sent' && <p role="status">Message sent</p>}
{status === 'Unable to send message' &&
<p role="alert">Unable to send message</p>}
</form>
);
}
it('shows success after a message is sent', async () => {
const user = userEvent.setup();
const sendMessage = vi.fn().mockResolvedValue(undefined);
render(<ContactForm sendMessage={sendMessage} />);
await user.click(
screen.getByRole('button', { name: /send message/i })
);
expect(await screen.findByText(/message sent/i)).toBeInTheDocument();
expect(sendMessage).toHaveBeenCalledTimes(1);
});
findBy queries are useful when an element is expected to appear asynchronously. For more complex asynchronous workflows, also test loading states, rejected requests, disabled submit buttons, and retry behaviour.
20. Testing Prevented Default Behaviour
Forms normally submit through the browser's default behaviour. React applications often call event.preventDefault() to stop a page reload and handle submission in JavaScript. Tests should focus on the user-visible outcome and whether the submission callback runs correctly.
function SearchForm({ onSearch }) {
return (
<form
onSubmit={(event) => {
event.preventDefault();
onSearch();
}}
>
<button type="submit">Search</button>
</form>
);
}
it('runs the search handler on submit', async () => {
const user = userEvent.setup();
const onSearch = vi.fn();
render(<SearchForm onSearch={onSearch} />);
await user.click(screen.getByRole('button', { name: /search/i }));
expect(onSearch).toHaveBeenCalledTimes(1);
});
21. user-event vs fireEvent
Both user-event and fireEvent are provided by the Testing Library ecosystem, but they serve different purposes.
| Feature |
user-event |
fireEvent |
| Purpose |
Simulates higher-level user interactions. |
Dispatches a specific DOM event. |
| Typing |
user.type() |
Requires manually dispatching input-related events. |
| Clicking |
user.click() |
fireEvent.click() |
| Realism |
Generally closer to user behaviour. |
Useful for targeted event-level tests. |
| Async usage |
Interactions are generally awaited. |
Event dispatch is generally synchronous. |
Recommendation: Prefer user-event for most everyday form and interaction tests. Use fireEvent when a lower-level event dispatch is specifically required.
22. Common Testing Library Queries
| Query |
Purpose |
getByRole() |
Finds an element by its accessible role and optional name. |
getByLabelText() |
Finds a form field using its label. |
getByPlaceholderText() |
Finds a field using placeholder text. |
getByText() |
Finds an element by visible text. |
queryByText() |
Useful for checking whether an element is absent. |
findByText() |
Waits for matching text to appear asynchronously. |
getByDisplayValue() |
Finds a form control by its current displayed value. |
Use accessible queries such as roles and labels whenever possible. They encourage accessible markup and make tests easier to understand.
23. Best Practices for Testing Forms and Events
- Test the form from the user's perspective.
- Prefer
getByRole and getByLabelText for selecting controls.
- Use
userEvent.setup() and await user interactions.
- Test both valid and invalid input.
- Check that invalid data does not reach the submission callback.
- Verify success, error, and loading messages.
- Test checkboxes, radio buttons, dropdowns, and keyboard navigation when applicable.
- Use mock functions for callbacks and external operations.
- Wait for asynchronous results with
findBy or waitFor when necessary.
- Avoid testing internal React state directly when visible behaviour can be tested instead.
- Keep tests independent so one test does not rely on another test's execution.
- Use realistic test data, including whitespace, empty values, and invalid input.
- Remember that frontend validation does not replace server-side validation.
24. Common Mistakes to Avoid
| Mistake |
Better Approach |
| Not awaiting user-event interactions. |
Use await user.type() and await user.click(). |
| Finding fields only through implementation-specific selectors. |
Prefer accessible labels and roles. |
| Testing only successful submissions. |
Test validation failures and error states as well. |
| Assuming async results appear immediately. |
Use asynchronous queries when appropriate. |
| Testing internal state instead of behaviour. |
Assert on visible messages, selected values, and callback arguments. |
| Ignoring native browser validation. |
Account for HTML validation when testing custom validation logic. |
| Using a reset button without resetting controlled state. |
Reset React state explicitly in controlled forms. |
| Relying only on frontend validation. |
Validate submitted data on the server as well. |
25. Practical Project: Testing a Contact Form
Build a contact form that accepts a user's name, email, and message. Validate the required fields and display a confirmation after a successful submission.
Project Requirements
- Provide name, email, and message fields.
- Use accessible labels for all fields.
- Prevent submission when required fields are invalid.
- Display a validation message when input is incorrect.
- Call a submission callback when the form is valid.
- Display a success message after submission.
- Test text entry, validation, button clicks, and submission.
Sample Contact Form Component
import { useState } from 'react';
export default function ContactForm({ onSend }) {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const [status, setStatus] = useState('');
function handleSubmit(event) {
event.preventDefault();
if (!name.trim() || !email.trim() || !message.trim()) {
setStatus('Please complete all fields');
return;
}
onSend({ name: name.trim(), email, message });
setStatus('Your message has been submitted');
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="contact-name">Name</label>
<input
id="contact-name"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<label htmlFor="contact-email">Email</label>
<input
id="contact-email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<label htmlFor="contact-message">Message</label>
<textarea
id="contact-message"
value={message}
onChange={(event) => setMessage(event.target.value)}
/>
<button type="submit">Send Message</button>
{status && <p role="status">{status}</p>}
</form>
);
}
Sample Contact Form Test
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi } from 'vitest';
import ContactForm from './ContactForm';
describe('ContactForm', () => {
it('submits completed contact details', async () => {
const user = userEvent.setup();
const onSend = vi.fn();
render(<ContactForm onSend={onSend} />);
await user.type(screen.getByLabelText(/name/i), 'Aarav');
await user.type(
screen.getByLabelText(/email/i),
'[email protected]'
);
await user.type(
screen.getByLabelText(/message/i),
'I would like more information.'
);
await user.click(
screen.getByRole('button', { name: /send message/i })
);
expect(onSend).toHaveBeenCalledWith({
name: 'Aarav',
email: '[email protected]',
message: 'I would like more information.'
});
expect(screen.getByRole('status')).toHaveTextContent(
/your message has been submitted/i
);
});
it('does not submit when fields are empty', async () => {
const user = userEvent.setup();
const onSend = vi.fn();
render(<ContactForm onSend={onSend} />);
await user.click(
screen.getByRole('button', { name: /send message/i })
);
expect(onSend).not.toHaveBeenCalled();
expect(screen.getByRole('status')).toHaveTextContent(
/please complete all fields/i
);
});
});
Run the tests with npm test. To run the Vitest suite once without watch mode, use npm run test:run if you added that script.
26. Interview Questions and Answers
Q1. What is form testing in React?
Form testing verifies that input fields, validation rules, submission handlers, and user feedback work correctly.
Q2. What is event testing?
Event testing checks how a component responds to user actions such as clicking, typing, selecting options, or submitting a form.
Q3. What is React Testing Library?
React Testing Library is a library for testing React components through their rendered interface and user-visible behaviour.
Q4. Why use user-event?
It simulates higher-level user interactions, making tests more representative of actual typing, clicking, selecting, and keyboard use.
Q5. What is the purpose of preventDefault()?
event.preventDefault() prevents the browser's default action for an event, such as normal form navigation during submission.
Q6. What is a mock function?
A mock function records how it was called and with which arguments. It helps test callbacks without executing the original external operation.
Q7. How do you test an invalid form submission?
Enter invalid data, attempt submission, verify that the expected validation feedback appears, and confirm that the submission callback is not called.
Q8. What is the difference between getBy and findBy queries?
getBy queries look for an element immediately and throw an error if it is not found. findBy queries wait for an element to appear asynchronously.
Q9. How do you test a checkbox?
Find it by its accessible role and name, click it using user-event, and verify its checked state with toBeChecked().
Q10. Why should tests use accessible labels?
Accessible labels make fields easier to use with assistive technology and let tests locate form controls in a user-oriented way.
Q11. How do you test asynchronous submission?
Mock the asynchronous operation, perform the submission, and wait for the expected loading, success, or error state.
Q12. Should frontend form validation replace backend validation?
No. Frontend validation improves user experience, but the server must independently validate and safely process submitted data.
27. Revision Checklist
- Understand React form fields and event handlers.
- Know how to configure a React testing environment.
- Use React Testing Library to render components.
- Find fields with labels and accessible roles.
- Test text input, checkboxes, radio buttons, and dropdowns.
- Test form submission and mock callback functions.
- Verify validation messages for invalid input.
- Test keyboard navigation and focus behaviour.
- Handle asynchronous interactions and server responses.
- Understand the difference between user-event and fireEvent.
- Write tests for both success and failure scenarios.
- Run the test suite and review failures before releasing the application.
28. Conclusion
Testing forms and events in React helps ensure that users can enter information, interact with controls, receive useful validation feedback, and submit data reliably. React Testing Library, user-event, and a test runner such as Vitest or Jest provide tools for verifying these behaviours. A strong test suite should cover normal interactions, invalid inputs, accessibility, asynchronous operations, and failure scenarios.
To learn more about React development, explore the JustAcademy React JS Training Course or Register for React JS Course Demo.