Sub topic 9
Testing forms end to end
This chapter assumes you can write a basic test with render, screen, and role-based queries. It also assumes you know how user-event simulates clicks and typing, and that you know the jest-dom matchers. Here you will combine them to test a complete form, from typing to submission.
What an end-to-end form test covers
A form test follows the same steps a person takes:
- Find each field the way a user would, by its label.
- Type values and choose options.
- Click the submit button.
- Check the outcome: the callback received the right data, or the page shows an error message.
You do not read component state. You check what the user sees and what the component sends to its parent.
A basic submission test
The component below keeps the email in state and calls an injected onSubmit prop when the form is submitted.
// 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]' });
});In Vitest, use vi.fn() instead of jest.fn().
The test never touches the email state variable. It types into the field and checks the value that reached onSubmit. If you later rename the state or move to a different form library, the test still passes.
Why getByLabelText matters
getByLabelText('Email') only succeeds if the <label> is correctly linked to the input, here through htmlFor and id. A test that finds the field by label therefore also checks that the form is accessible. If the link is missing, the query fails, and screen reader users would have hit the same problem.
Where the flow runs
The diagram shows what happens during the test.
Testing validation messages
Many forms show errors instead of submitting. Test both paths: invalid input shows a message and does not call the callback, and valid input does the opposite.
// SignupForm.jsx
import { useState } from 'react';
export function SignupForm({ onSubmit }) {
const [email, setEmail] = useState('');
const [error, setError] = useState('');
return (
<form
onSubmit={(e) => {
e.preventDefault();
if (!email.includes('@')) {
setError('Enter a valid email');
return;
}
setError('');
onSubmit({ email });
}}
>
<label htmlFor="signup-email">Email</label>
<input
id="signup-email"
value={email}
onChange={(e) => setEmail(e.target.value)}
aria-invalid={error ? 'true' : 'false'}
/>
{error && <p 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');
expect(screen.getByLabelText('Email')).toBeInvalid();
expect(handleSubmit).not.toHaveBeenCalled();
});
test('clears the error and submits a valid email', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn();
render(<SignupForm onSubmit={handleSubmit} />);
await user.type(screen.getByLabelText('Email'), '[email protected]');
await user.click(screen.getByRole('button', { name: 'Create account' }));
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
expect(handleSubmit).toHaveBeenCalledWith({ email: '[email protected]' });
});Notes on the choices:
- The error uses
role="alert", so the test can query it by role, and screen readers announce it. - The error is already in the DOM after the click because the component sets it synchronously, so
getByRoleworks. If validation ran asynchronously, you would usefindByRole. queryByRoleis the right variant for asserting that something is absent.toBeInvalidchecks thearia-invalidattribute, which is a user-facing signal.
Other field types
| Field | How to interact | Example |
|---|---|---|
| Text input | `user.type` | `await user.type(input, 'hello')` |
| Clear then type | `user.clear` then `user.type` | `await user.clear(input)` |
| Checkbox or radio | `user.click` | `await user.click(screen.getByRole('checkbox', { name: 'Remember me' }))` |
| Select | `user.selectOptions` | `await user.selectOptions(screen.getByLabelText('Country'), 'Norway')` |
After clicking a checkbox, assert with toBeChecked().
Common mistakes
- Using
fireEvent.changefor typing. It sets a value in one step and skips the keyboard events a real user produces. Preferuser.type. - Finding fields by placeholder or test ID when a label exists. Labels are higher priority and verify accessibility.
- Forgetting
awaitbefore ausercall. The assertion then runs before the interaction finishes. - Asserting on internal state instead of the callback arguments or visible output.
Exercise
In the SignupForm test for an invalid email, why is handleSubmit checked with not.toHaveBeenCalled(), and why is the alert found with getByRole('alert') rather than getByText?
Show answer
The test must confirm that invalid input blocks submission, and a missing call is the only observable proof of that, so not.toHaveBeenCalled() covers it. getByRole('alert') queries by the accessible role, which matches how assistive technology finds the message and also verifies the component marks the error as an alert. getByText would pass even if the error were plain text with no alert semantics.
Exercise
A test types into a field with user.type(screen.getByPlaceholderText('[email protected]'), 'ada'), and the form has a visible "Email" label. What would you change and why?
Show answer
Query by label with screen.getByLabelText('Email'). Label queries have higher priority than placeholder queries, and they fail if the label is not linked to the input, which catches an accessibility bug.