Test a React form submission
Fill in a form, click submit and assert the handler received the values, using user-event and a vi.fn onSubmit in React 19.
Test a form the way a user uses it: type into the fields and press the button, then check what was submitted.
import { test, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
function Signup({ onSubmit }) {
return (
<form
onSubmit={(event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
onSubmit({ email: data.get('email') });
}}
>
<label>
Email <input name="email" type="email" />
</label>
<button type="submit">Join</button>
</form>
);
}
test('submits the email', async () => {
const onSubmit = vi.fn();
const user = userEvent.setup();
render(<Signup onSubmit={onSubmit} />);
await user.type(screen.getByLabelText('Email'), '[email protected]');
await user.click(screen.getByRole('button', { name: 'Join' }));
expect(onSubmit).toHaveBeenCalledWith({ email: '[email protected]' });
}); ✓ signup.test.jsx (1 test)
Test Files 1 passed (1)
Tests 1 passed (1)user.click on a submit button fires the form's submit event, as a browser would, so you do not call fireEvent.submit. FormData reads the values from the DOM. See FormData.
Add a test for the invalid path, such as an empty field, to check the message and that onSubmit is not called.