How to Test User Interactions in React :👈 👉:How to Mock API Requests in React Tests

How to Test Forms in React

How to Test Forms in React

1. Introduction

Form testing verifies that a React form behaves correctly when users enter data, submit information, and interact with form controls.

Common scenarios include:

  • Entering text into input fields.
  • Validating required fields.
  • Checking email and password validation.
  • Displaying validation error messages.
  • Submitting valid form data.
  • Displaying success and error messages.
  • Preventing submission when the form is invalid.
  • Handling API failures.

React Testing Library allows us to test forms from the user's perspective instead of testing internal component implementation details.

2. Tools Required

ToolPurpose
React Testing LibraryRenders components and checks their behavior.
user-eventSimulates realistic user interactions such as typing and clicking.
VitestRuns test cases and provides assertions and mocking.
jest-domProvides convenient DOM assertions such as toBeInTheDocument().
jsdomProvides a browser-like DOM environment for tests.

3. Install Required Packages

For a React application using Vite, install the following development dependencies:

npm install -D vitest jsdom
npm install -D @testing-library/react
npm install -D @testing-library/user-event
npm install -D @testing-library/jest-dom

Configure Vitest

Update 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 src/test/setup.js:

import '@testing-library/jest-dom/vitest';

Add a test script to package.json:

{
  "scripts": {
    "test": "vitest",
    "test:run": "vitest run"
  }
}

4. Create a Sample React Form

Let's create a registration form with name, email, and password fields.

RegistrationForm.jsx

import { useState } from 'react';
function RegistrationForm({ onRegister }) {
  const [form, setForm] = useState({
    name: '',
    email: '',
    password: ''
  });
  const [errors, setErrors] = useState({});
  const [message, setMessage] = useState('');
  function handleChange(event) {
    const { name, value } = event.target;
    setForm(prev => ({
      ...prev,
      [name]: value
    }));
  }
  function validate() {
    const newErrors = {};
    if (!form.name.trim()) {
      newErrors.name = 'Name is required';
    }
    if (!form.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(form.email)) {
      newErrors.email = 'Enter a valid email';
    }
    if (!form.password) {
      newErrors.password = 'Password is required';
    } else if (form.password.length < 6) {
      newErrors.password =
        'Password must be at least 6 characters';
    }
    return newErrors;
  }
  async function handleSubmit(event) {
    event.preventDefault();
    setMessage('');
    const validationErrors = validate();
    setErrors(validationErrors);
    if (Object.keys(validationErrors).length > 0) {
      return;
    }
    try {
      await onRegister(form);
      setMessage('Registration successful');
    } catch {
      setMessage('Registration failed');
    }
  }
  return (
    <form onSubmit={handleSubmit}>
      <h2>Registration</h2>
      <label htmlFor="name">Name</label>
      <input
        id="name"
        name="name"
        value={form.name}
        onChange={handleChange}
      />
      {errors.name && <p role="alert">{errors.name}</p>}
      <label htmlFor="email">Email</label>
      <input
        id="email"
        name="email"
        type="email"
        value={form.email}
        onChange={handleChange}
      />
      {errors.email && <p role="alert">{errors.email}</p>}
      <label htmlFor="password">Password</label>
      <input
        id="password"
        name="password"
        type="password"
        value={form.password}
        onChange={handleChange}
      />
      {errors.password && (
        <p role="alert">{errors.password}</p>
      )}
      <button type="submit">Register</button>
      {message && <p role="status">{message}</p>}
    </form>
  );
}
export default RegistrationForm;

5. Test Form Rendering

First, verify that the form fields and submit button appear correctly.

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 all form fields', () => {
    render(
      <RegistrationForm onRegister={vi.fn()} />
    );
    expect(screen.getByLabelText(/name/i))
      .toBeInTheDocument();
    expect(screen.getByLabelText(/email/i))
      .toBeInTheDocument();
    expect(screen.getByLabelText(/password/i))
      .toBeInTheDocument();
    expect(
      screen.getByRole('button', { name: /register/i })
    ).toBeInTheDocument();
  });
});

What are we testing?

  • Whether all expected input fields are displayed.
  • Whether labels are correctly associated with inputs.
  • Whether the Register button is available.

6. Test Required Field Validation

When a user submits an empty form, validation errors should appear.

it('displays required field errors', async () => {
  const user = userEvent.setup();
  render(
    <RegistrationForm onRegister={vi.fn()} />
  );
  await user.click(
    screen.getByRole('button', { name: /register/i })
  );
  expect(screen.getByText('Name is required'))
    .toBeInTheDocument();
  expect(screen.getByText('Email is required'))
    .toBeInTheDocument();
  expect(screen.getByText('Password is required'))
    .toBeInTheDocument();
});

Important: This test verifies that invalid data is rejected before the registration callback is executed.

7. Test Input Field Changes

We should verify that users can enter information into form fields.

it('allows users to enter form details', async () => {
  const user = userEvent.setup();
  render(
    <RegistrationForm onRegister={vi.fn()} />
  );
  await user.type(
    screen.getByLabelText(/name/i),
    'John'
  );
  await user.type(
    screen.getByLabelText(/email/i),
    'john@example.com'
  );
  await user.type(
    screen.getByLabelText(/password/i),
    'secret123'
  );
  expect(screen.getByLabelText(/name/i))
    .toHaveValue('John');
  expect(screen.getByLabelText(/email/i))
    .toHaveValue('john@example.com');
  expect(screen.getByLabelText(/password/i))
    .toHaveValue('secret123');
});

What does toHaveValue() do?

It checks whether an input field contains the expected value.

8. Test Email Validation

We should verify that an invalid email address displays the correct validation message.

it('displays an error for invalid email', async () => {
  const user = userEvent.setup();
  render(
    <RegistrationForm onRegister={vi.fn()} />
  );
  await user.type(
    screen.getByLabelText(/name/i),
    'John'
  );
  await user.type(
    screen.getByLabelText(/email/i),
    'invalid-email'
  );
  await user.type(
    screen.getByLabelText(/password/i),
    'secret123'
  );
  await user.click(
    screen.getByRole('button', { name: /register/i })
  );
  expect(screen.getByText('Enter a valid email'))
    .toBeInTheDocument();
});

9. Test Successful Form Submission

When all fields contain valid information, the form should call the registration function and display a success message.

it('submits valid form data successfully', async () => {
  const user = userEvent.setup();
  const mockRegister = vi.fn().mockResolvedValue({});
  render(
    <RegistrationForm onRegister={mockRegister} />
  );
  await user.type(
    screen.getByLabelText(/name/i),
    'John'
  );
  await user.type(
    screen.getByLabelText(/email/i),
    'john@example.com'
  );
  await user.type(
    screen.getByLabelText(/password/i),
    'secret123'
  );
  await user.click(
    screen.getByRole('button', { name: /register/i })
  );
  expect(mockRegister).toHaveBeenCalledWith({
    name: 'John',
    email: 'john@example.com',
    password: 'secret123'
  });
  expect(
    await screen.findByText('Registration successful')
  ).toBeInTheDocument();
});

Explanation:

  • vi.fn() creates a mock function.
  • mockResolvedValue() makes the mock return a successful Promise.
  • toHaveBeenCalledWith() checks the submitted data.
  • findByText() waits for the success message to appear.

10. Test API or Submission Failure

Forms often submit data to an API. We should also test what happens when the API request fails.

it('displays an error when registration fails', async () => {
  const user = userEvent.setup();
  const mockRegister = vi.fn()
    .mockRejectedValue(new Error('Server error'));
  render(
    <RegistrationForm onRegister={mockRegister} />
  );
  await user.type(
    screen.getByLabelText(/name/i),
    'John'
  );
  await user.type(
    screen.getByLabelText(/email/i),
    'john@example.com'
  );
  await user.type(
    screen.getByLabelText(/password/i),
    'secret123'
  );
  await user.click(
    screen.getByRole('button', { name: /register/i })
  );
  expect(
    await screen.findByText('Registration failed')
  ).toBeInTheDocument();
});

This test ensures that the form handles a rejected API request and provides feedback to the user.

11. Test That Invalid Forms Are Not Submitted

Displaying validation messages is not enough. We must also verify that the submission function is not called when the form contains invalid information.

it('does not submit invalid form data', async () => {
  const user = userEvent.setup();
  const mockRegister = vi.fn();
  render(
    <RegistrationForm onRegister={mockRegister} />
  );
  await user.click(
    screen.getByRole('button', { name: /register/i })
  );
  expect(mockRegister).not.toHaveBeenCalled();
});

This is important because invalid data should not be sent to the backend.

12. Test Checkbox and Select Fields

Forms may also contain checkboxes and dropdown lists. React Testing Library supports testing these controls.

Checkbox example

Sample component:

function TermsForm() {
  const [accepted, setAccepted] = useState(false);
  return (
    <div>
      <label>
        <input
          type="checkbox"
          checked={accepted}
          onChange={event =>
            setAccepted(event.target.checked)
          }
        />
        Accept terms and conditions
      </label>
      <p>{accepted ? 'Accepted' : 'Not accepted'}</p>
    </div>
  );
}

Test:

it('allows users to accept terms', async () => {
  const user = userEvent.setup();
  render(<TermsForm />);
  const checkbox = screen.getByRole('checkbox', {
    name: /accept terms and conditions/i
  });
  await user.click(checkbox);
  expect(checkbox).toBeChecked();
  expect(screen.getByText('Accepted'))
    .toBeInTheDocument();
});

Dropdown example

Sample component:

function CountryForm() {
  const [country, setCountry] = useState('');
  return (
    <div>
      <label htmlFor="country">Country</label>
      <select
        id="country"
        value={country}
        onChange={event => setCountry(event.target.value)}
      >
        <option value="">Select country</option>
        <option value="india">India</option>
        <option value="usa">USA</option>
      </select>
      <p>Selected: {country}</p>
    </div>
  );
}

Test:

it('allows users to select a country', async () => {
  const user = userEvent.setup();
  render(<CountryForm />);
  const dropdown = screen.getByLabelText(/country/i);
  await user.selectOptions(dropdown, 'india');
  expect(dropdown).toHaveValue('india');
  expect(screen.getByText('Selected: india'))
    .toBeInTheDocument();
});

13. Test Form Reset

If a form has a Reset button, verify that it clears the entered values.

Example component:

function ContactForm() {
  const [name, setName] = useState('');
  return (
    <form>
      <label htmlFor="contact-name">Name</label>
      <input
        id="contact-name"
        value={name}
        onChange={event => setName(event.target.value)}
      />
      <button
        type="button"
        onClick={() => setName('')}
      >
        Reset
      </button>
    </form>
  );
}

Test:

it('clears the form when reset is clicked', async () => {
  const user = userEvent.setup();
  render(<ContactForm />);
  const nameInput = screen.getByLabelText(/name/i);
  await user.type(nameInput, 'John');
  expect(nameInput).toHaveValue('John');
  await user.click(
    screen.getByRole('button', { name: /reset/i })
  );
  expect(nameInput).toHaveValue('');
});

14. Important Testing Library Queries

QueryPurpose
getByLabelText()Finds inputs using their labels.
getByRole()Finds elements using accessible roles.
getByText()Finds elements using visible text.
getByPlaceholderText()Finds inputs using placeholder text.
queryByText()Checks whether an element exists without throwing when it is absent.
findByText()Waits for an element to appear asynchronously.

15. Important user-event Methods

MethodPurpose
user.type()Enters text into an input.
user.clear()Clears an input field.
user.click()Clicks a button or other interactive element.
user.selectOptions()Selects an option in a dropdown.
user.keyboard()Simulates keyboard input.
user.tab()Moves focus to the next focusable element.

16. fireEvent vs user-event

fireEventuser-event
Dispatches a specific DOM event.Simulates higher-level user interactions.
Useful for specialized event testing.Better for typical form interactions.
Does not reproduce the complete sequence of browser interactions.Performs more realistic interaction sequences.

Recommendation: Prefer user-event for normal form testing. Use fireEvent when you specifically need to dispatch an individual event.

17. Best Practices for Testing React Forms

  • Test forms from the user's perspective.
  • Use getByLabelText() for accessible form inputs.
  • Use userEvent for typing, clicking, and selecting options.
  • Test both valid and invalid form submissions.
  • Verify that validation messages appear correctly.
  • Verify that invalid data is not submitted.
  • Test API success and failure scenarios.
  • Test checkboxes, dropdowns, radio buttons, and reset buttons.
  • Use findBy... queries for elements that appear asynchronously.
  • Avoid testing internal React state directly.
  • Keep individual test cases focused on one behavior.
  • Use accessible labels and roles in your components.
  • Do not rely only on frontend validation; the backend must validate incoming data too.

18. Common Mistakes

MistakeBetter approach
Testing only successful submissions.Test invalid input and API failures too.
Using placeholder text instead of labels.Provide proper accessible labels.
Using getByText() for every element.Prefer role and label queries when appropriate.
Not awaiting user interactions.Use await with user-event methods.
Checking internal component state.Verify visible results and user-observable behavior.
Ignoring API failures.Mock rejected Promises and test error messages.
Testing only individual fields.Also test the complete form submission workflow.

19. Interview Questions and Answers

1. How do you test forms in React?

We use React Testing Library and user-event to simulate user interactions. We test input changes, validation, successful submission, invalid submission, and API failure scenarios.

2. How do you test required field validation?

Submit the form without entering any values and verify that the expected validation messages appear.

3. How do you test form submission?

Enter valid information, click the submit button, and verify that the submission callback is called with the expected data.

4. How do you test API calls in forms?

Mock the API function using vi.fn(). Use mockResolvedValue() for successful responses and mockRejectedValue() for failures.

5. What is the difference between getByText() and findByText()?

getByText() searches immediately and throws an error if the element is missing. findByText() waits for the element to appear and returns a Promise.

6. Why should we use user-event instead of fireEvent?

user-event simulates realistic user interactions, while fireEvent dispatches individual DOM events. For most form tests, user-event is preferred.

7. How do you test checkbox fields?

Find the checkbox using getByRole('checkbox'), click it using user-event, and verify its state using toBeChecked().

8. Why should we test invalid form submissions?

To ensure invalid data is rejected, validation messages are displayed, and the submission function is not called.

9. What is the purpose of vi.fn()?

vi.fn() creates a mock function. It helps us check whether a function was called, how many times it was called, and what arguments were passed.

10. Should we test React component state directly?

Generally, no. React Testing Library encourages testing observable behavior, such as displayed messages, input values, and user interactions.

20. Summary

Testing React forms is an important part of frontend application quality. A good form test suite should cover the complete user journey, from entering information to receiving a submission result.

Remember these important points:

  • render() – Renders the React form.
  • screen – Finds elements in the rendered form.
  • userEvent – Simulates user interactions.
  • vi.fn() – Creates mock functions.
  • toHaveValue() – Checks input values.
  • toBeInTheDocument() – Checks whether an element exists.
  • toBeChecked() – Checks checkbox state.
  • findByText() – Waits for asynchronous UI updates.

**The main principle:** Test what users can see and do, rather than how the component internally manages its state.

🔙
How to Test User Interactions in React :👈 👉:How to Mock API Requests in React Tests

Comments and Discussion