Sub topic 9
Testing forms end to end
This chapter assumes you can write a React function component with state, and that you have a Jest or Vitest project configured with jsdom and jest-dom (covered in the setup chapter). It also assumes you know how render, screen, role and label queries, and user-event work. Here you combine them to test a whole form: finding fields, typing, submitting, validating, and checking what the user sees.
What "end to end" means for a form
A form test in React Testing Library (RTL) is not a browser test. It runs in jsdom, a simulated DOM in Node. "End to end" here means the test covers the whole user path inside one component: the user finds a field, types a value, submits, and sees a result. The test never reads component state. It only uses the screen and the callbacks you pass in.
A form test usually follows five steps:
- Render the form with a mock callback for submission.
- Find each field by its label.
- Type or select values with
user-event. - Click the submit button.
- Assert on the callback arguments or on the visible message.
A basic submit test
Start with the login form. It keeps its value in state and calls onSubmit with the typed email.
// 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]' });
});Three details matter here.
getByLabelText('Email')finds the input through the<label>. If thehtmlForandiddo not match, the query fails. That failure is useful: a screen reader user would also not get a label for that field.user.typeclicks the field and then sends one keystroke at a time. Each keystroke fireskeydown,input, andkeyupevents, so the controlled input updates the way it would in a browser.toHaveBeenCalledWithchecks the data that crossed the boundary of the component. In Vitest, usevi.fn()instead ofjest.fn().
Submitting with the keyboard
Users often press Enter instead of clicking. user.type accepts special key syntax in braces, so you can cover both paths.
test('submits when the user presses Enter in the field', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn();
render(<LoginForm onSubmit={handleSubmit} />);
await user.type(screen.getByLabelText('Email'), '[email protected]{Enter}');
expect(handleSubmit).toHaveBeenCalledTimes(1);
});This works because the form has a submit button, and jsdom follows the browser rule for implicit submission. If you replace the button with a div that has an onClick, this test fails, and it should, because the real form would also break for keyboard users.
Finding fields by label
Label queries are the first choice for form controls. The table shows how common field types map to queries.
| Control | Markup | Query |
|---|---|---|
| Text input | `<label for>` plus `<input>` | `getByLabelText('Email')` or `getByRole('textbox', { name: 'Email' })` |
| Checkbox | `<input type="checkbox">` with a label | `getByRole('checkbox', { name: 'Remember me' })` |
| Radio button | `<input type="radio">` with a label | `getByRole('radio', { name: 'Monthly' })` |
| Select | `<select>` with a label | `getByRole('combobox', { name: 'Country' })` |
| Password input | `<input type="password">` | `getByLabelText('Password')` (it has no role) |
| Submit button | `<button type="submit">` | `getByRole('button', { name: 'Sign in' })` |
Password inputs have no ARIA role, so getByRole cannot find them. Use getByLabelText for those.
If a field has no visible label, such as a search box with only an icon, give it an aria-label. The label query then finds it, and the page is more accessible too.
Checkboxes, radios, and selects
user-event has a method for each control, and jest-dom has matching assertions.
// PlanForm.jsx
import { useState } from 'react';
export function PlanForm({ onSubmit }) {
const [plan, setPlan] = useState('monthly');
const [country, setCountry] = useState('');
const [terms, setTerms] = useState(false);
return (
<form
onSubmit={(e) => {
e.preventDefault();
onSubmit({ plan, country, terms });
}}
>
<fieldset>
<legend>Billing</legend>
<label>
<input
type="radio"
name="plan"
value="monthly"
checked={plan === 'monthly'}
onChange={() => setPlan('monthly')}
/>
Monthly
</label>
<label>
<input
type="radio"
name="plan"
value="yearly"
checked={plan === 'yearly'}
onChange={() => setPlan('yearly')}
/>
Yearly
</label>
</fieldset>
<label htmlFor="country">Country</label>
<select id="country" value={country} onChange={(e) => setCountry(e.target.value)}>
<option value="">Choose...</option>
<option value="se">Sweden</option>
<option value="nz">New Zealand</option>
</select>
<label>
<input type="checkbox" checked={terms} onChange={(e) => setTerms(e.target.checked)} />
Accept terms
</label>
<button type="submit">Subscribe</button>
</form>
);
}
// PlanForm.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { PlanForm } from './PlanForm';
test('submits the chosen plan, country, and terms', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn();
render(<PlanForm onSubmit={handleSubmit} />);
expect(screen.getByRole('radio', { name: 'Monthly' })).toBeChecked();
await user.click(screen.getByRole('radio', { name: 'Yearly' }));
await user.selectOptions(screen.getByRole('combobox', { name: 'Country' }), 'nz');
await user.click(screen.getByRole('checkbox', { name: 'Accept terms' }));
expect(screen.getByRole('radio', { name: 'Yearly' })).toBeChecked();
expect(screen.getByRole('checkbox', { name: 'Accept terms' })).toBeChecked();
await user.click(screen.getByRole('button', { name: 'Subscribe' }));
expect(handleSubmit).toHaveBeenCalledWith({
plan: 'yearly',
country: 'nz',
terms: true,
});
});Notes on this test:
selectOptionsaccepts the option'svalueor its visible text. Passing'nz'or'New Zealand'both work.- A label that wraps the input (
<label><input /> Monthly</label>) works withgetByRole(..., { name })because the wrapped text becomes the accessible name. toBeCheckedis a jest-dom matcher. It works for checkboxes, radios, and elements withrole="checkbox"andaria-checked.- The test asserts the checked state before the final submit. Intermediate assertions give a clearer failure than a wrong object in
toHaveBeenCalledWith.
Validation and error messages
A form that validates should show errors the user can read. Test those messages, not the internal errors state.
// SignupForm.jsx
import { useState } from 'react';
export function SignupForm({ onSubmit }) {
const [email, setEmail] = useState('');
const [error, setError] = useState('');
function handleSubmit(e) {
e.preventDefault();
if (!email.includes('@')) {
setError('Enter a valid email address');
return;
}
setError('');
onSubmit({ email });
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="signup-email">Email</label>
<input
id="signup-email"
value={email}
onChange={(e) => setEmail(e.target.value)}
aria-invalid={error ? 'true' : 'false'}
aria-describedby={error ? 'signup-error' : undefined}
/>
{error && (
<p id="signup-error" role="alert">
{error}
</p>
)}
<button type="submit">Create account</button>
</form>
);
}
// SignupForm.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SignupForm } from './SignupForm';
test('shows an error and does not submit an invalid email', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn();
render(<SignupForm onSubmit={handleSubmit} />);
await user.type(screen.getByLabelText('Email'), 'not-an-email');
await user.click(screen.getByRole('button', { name: 'Create account' }));
expect(screen.getByRole('alert')).toHaveTextContent('Enter a valid email address');
expect(screen.getByLabelText('Email')).toBeInvalid();
expect(handleSubmit).not.toHaveBeenCalled();
});
test('clears the error and submits after the user fixes the email', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn();
render(<SignupForm onSubmit={handleSubmit} />);
const input = screen.getByLabelText('Email');
await user.type(input, 'nope');
await user.click(screen.getByRole('button', { name: 'Create account' }));
await user.clear(input);
await user.type(input, '[email protected]');
await user.click(screen.getByRole('button', { name: 'Create account' }));
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
expect(handleSubmit).toHaveBeenCalledWith({ email: '[email protected]' });
});Key points:
- The error is rendered synchronously after the click, so
getByRole('alert')is correct. UsefindByonly when the message appears after async work. queryByRoleis the right variant for "not present", becausegetBywould throw beforenot.toBeInTheDocument()could run.toBeInvalidchecksaria-invalidand native validity. Asserting it confirms that assistive technology can tell the field is in error.user.clearempties a field. Do not simulate this withtype(input, '').
Async submission
Real forms usually call an API. Inject the submit function, resolve or reject it, and assert on what the user sees: a disabled button while pending, then a success or failure message.
// ContactForm.jsx
import { useState } from 'react';
export function ContactForm({ send }) {
const [message, setMessage] = useState('');
const [status, setStatus] = useState('idle');
async function handleSubmit(e) {
e.preventDefault();
setStatus('sending');
try {
await send({ message });
setStatus('sent');
} catch {
setStatus('error');
}
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="message">Message</label>
<textarea id="message" value={message} onChange={(e) => setMessage(e.target.value)} />
<button type="submit" disabled={status === 'sending'}>
{status === 'sending' ? 'Sending...' : 'Send'}
</button>
{status === 'sent' && <p>Thanks, your message was sent.</p>}
{status === 'error' && <p role="alert">Something went wrong. Try again.</p>}
</form>
);
}
// ContactForm.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ContactForm } from './ContactForm';
test('shows a success message after sending', async () => {
const user = userEvent.setup();
const send = jest.fn().mockResolvedValue();
render(<ContactForm send={send} />);
await user.type(screen.getByLabelText('Message'), 'Hello there');
await user.click(screen.getByRole('button', { name: 'Send' }));
expect(await screen.findByText('Thanks, your message was sent.')).toBeInTheDocument();
expect(send).toHaveBeenCalledWith({ message: 'Hello there' });
});
test('shows an error when sending fails', async () => {
const user = userEvent.setup();
const send = jest.fn().mockRejectedValue(new Error('network'));
render(<ContactForm send={send} />);
await user.type(screen.getByLabelText('Message'), 'Hello there');
await user.click(screen.getByRole('button', { name: 'Send' }));
expect(await screen.findByRole('alert')).toHaveTextContent('Something went wrong');
expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled();
});To check the pending state, return a promise you control, so the form stays in the "sending" state until you resolve it.
test('disables the button while the request is pending', async () => {
const user = userEvent.setup();
let resolveSend;
const send = jest.fn(
() =>
new Promise((resolve) => {
resolveSend = resolve;
})
);
render(<ContactForm send={send} />);
await user.type(screen.getByLabelText('Message'), 'Hi');
await user.click(screen.getByRole('button', { name: 'Send' }));
expect(screen.getByRole('button', { name: 'Sending...' })).toBeDisabled();
resolveSend();
expect(await screen.findByText('Thanks, your message was sent.')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled();
});The final findByText also waits for React to finish the state update caused by resolveSend(). If you ended the test right after calling resolveSend(), React would log an "not wrapped in act" warning because the update lands after the test is done.
Common form-testing mistakes
- Reading state instead of output. Do not assert on
emailstate. Assert on the input's value withtoHaveValue('[email protected]')or on the callback's arguments. - Using
fireEvent.changefor typing. It sets the value in one event and skips focus, keydown, and keyup. Useuser.type. KeepfireEventfor eventsuser-eventdoes not model. - Forgetting
await. Everyuser-eventcall returns a promise. Withoutawait, the assertion runs before the interaction finishes, and the failure looks random. - Querying by placeholder. A placeholder is not a label. It disappears while typing and many screen readers do not announce it as a name. Add a real label.
- Asserting a "valid" form only. Test at least one invalid path. Bugs in validation usually hide there.
- Reusing one
useracross tests. CalluserEvent.setup()inside each test, so pointer and keyboard state do not leak.
Checking field values
Sometimes a form loads initial data, such as an edit profile page. Assert on what the field shows with toHaveValue, and on the whole form with toHaveFormValues.
test('shows the saved values in the edit form', () => {
render(<PlanForm onSubmit={() => {}} />);
expect(screen.getByRole('combobox', { name: 'Country' })).toHaveValue('');
expect(screen.getByRole('radio', { name: 'Monthly' })).toBeChecked();
});toHaveFormValues reads every named control in a form element. It needs the form to be found, which requires an accessible name on the form (aria-label="Billing form") so you can use getByRole('form', { name: 'Billing form' }). Without a name, a <form> has no form role.
Exercise
A SignupForm test types a bad email, clicks submit, and then runs expect(screen.getByRole('alert')).not.toBeInTheDocument() after the user corrects it. The test throws an error before reaching the assertion. Which query variant fixes it, and why does the original fail?
Show answer
Use queryByRole('alert'). getBy throws when no matching element exists, so the error is thrown inside the expect(...) argument before not.toBeInTheDocument() runs. queryBy returns null when nothing matches, and jest-dom's not.toBeInTheDocument() accepts null.
Exercise
Write the user actions (not the assertions) for a test that selects "Sweden" in a select labelled "Country", then submits by pressing Enter inside a text field labelled "Name". Assume user comes from userEvent.setup().
Show answer
await user.selectOptions(screen.getByRole('combobox', { name: 'Country' }), 'Sweden'); then await user.type(screen.getByLabelText('Name'), 'Ada{Enter}');. The {Enter} key descriptor triggers implicit submission, which works only if the form has a submit button.
Exercise
A form test passes locally but sometimes fails in CI with the callback "not called". The test uses user.click(screen.getByRole('button', { name: 'Send' })) without await. What is the cause and the fix?
Show answer
user-event methods are asynchronous and return promises. Without await, the assertion can run before the click and its resulting events finish. Add await to every user.* call and make the test function async.