Skip to content
jshacks.dev
Testing

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.

1 min read
Summarize in AI

Test a form the way a user uses it: type into the fields and press the button, then check what was submitted.

signup.test.jsxJSX
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]' });
});
Text
 ✓ 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.

Also inFrameworks
Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.