Testing React Form onSubmit with Formik and React Testing Library: A Step-by-Step Guide (2026)

Learn to test React forms with Formik and React Testing Library. Ensure correct form submission and validations for better user experiences.

Testing React Form onSubmit with Formik and React Testing Library: A Step-by-Step Guide (2026)

Testing React Form onSubmit with Formik and React Testing Library: A Step-by-Step Guide (2026)

Form validation and submission are integral parts of modern web applications. As React applications grow, ensuring that forms behave as expected becomes crucial. Formik, coupled with React Testing Library, provides a robust solution for form handling and testing. In this tutorial, you will learn how to effectively test a simple React form using Formik and React Testing Library.

Key Takeaways

  • Learn to set up Formik for form handling in React.
  • Understand how to use React Testing Library to test form submissions.
  • Identify common issues and troubleshooting techniques in React form testing.
  • Gain insights into best practices for testing form validations and submissions.

Testing forms ensures that your application captures and processes user inputs correctly. This tutorial will guide you through setting up a basic React form using Formik, writing tests for form submission with React Testing Library, and understanding common pitfalls in form testing.

Prerequisites

  • Basic understanding of React and JavaScript (ES6+).
  • Node.js and npm/yarn installed on your machine.
  • Familiarity with Formik and React Testing Library.
  • An IDE or text editor of your choice.

Step 1: Set Up Your React Project

Start by setting up a new React project. If you haven't already, you can create one using Create React App:

npx create-react-app formik-testing

Navigate into your project directory:

cd formik-testing

Step 2: Install Formik and React Testing Library

Install the necessary dependencies for Formik and React Testing Library:

npm install formik @testing-library/react @testing-library/jest-dom

These libraries will enable form handling and testing functionalities.

Step 3: Create the SignUpForm Component

Create a new component called SignUpForm.js in the src directory:

import React from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';

const SignUpForm = () => {
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
      password: ''
    },
    validationSchema: Yup.object({
      firstName: Yup.string()
        .max(15, 'Must be 15 characters or less')
        .required('Required'),
      lastName: Yup.string()
        .max(20, 'Must be 20 characters or less')
        .required('Required'),
      email: Yup.string()
        .email('Invalid email address')
        .required('Required'),
      password: Yup.string()
        .min(8, 'Password must be at least 8 characters long')
        .required('Required')
    }),
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    }
  });

  return (
    
      First Name
      
      {formik.touched.firstName && formik.errors.firstName ? (
        {formik.errors.firstName}
      ) : null}

      Last Name
      
      {formik.touched.lastName && formik.errors.lastName ? (
        {formik.errors.lastName}
      ) : null}

      Email Address
      
      {formik.touched.email && formik.errors.email ? (
        {formik.errors.email}
      ) : null}

      Password
      
      {formik.touched.password && formik.errors.password ? (
        {formik.errors.password}
      ) : null}

      Submit
    
  );
};

export default SignUpForm;

This component uses Formik to manage form state and Yup for validation. It includes fields for first name, last name, email, and password.

Step 4: Write Tests for Form Submission

Create a test file for the form, SignUpForm.test.js, in the src directory:

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import SignUpForm from './SignUpForm';

// Mock the alert function
window.alert = jest.fn();

test('submits the form with correct values', async () => {
  render();

  // Fill out the form
  fireEvent.change(screen.getByLabelText(/first name/i), {
    target: { value: 'John' }
  });
  fireEvent.change(screen.getByLabelText(/last name/i), {
    target: { value: 'Dee' }
  });
  fireEvent.change(screen.getByLabelText(/email/i), {
    target: { value: 'john.dee@someemail.com' }
  });
  fireEvent.change(screen.getByLabelText(/password/i), {
    target: { value: 'password123' }
  });

  // Submit the form
  fireEvent.click(screen.getByRole('button', { name: /submit/i }));

  // Check the alert was called with correct values
  expect(window.alert).toHaveBeenCalledWith(
    JSON.stringify({
      firstName: 'John',
      lastName: 'Dee',
      email: 'john.dee@someemail.com',
      password: 'password123'
    }, null, 2)
  );
});

This test simulates typing into each form field and clicking the submit button, then checks that the alert function is called with the correct form values.

Common Errors/Troubleshooting

If your test fails with a message like "Number of calls: 0", ensure that:

  • The form fields have the correct id or name attributes that match the selectors used in the test.
  • The onSubmit function is correctly set up and the form is being submitted with the correct button.
  • The alert function or any other side effect is correctly mocked and verified.

Testing forms with Formik and React Testing Library ensures that your components work as expected and provide consistent user experiences. By following this guide, you can confidently write tests for your React forms.

Expected Output

After running your tests with npm test, you should see that all tests pass, confirming that the form submits correctly when all fields are filled out properly.

Frequently Asked Questions

Why is my form submission test failing?

Check if the form fields have the correct ids and if the onSubmit function is properly set up and connected.

How do I test form validation errors?

Simulate form input with invalid data and check for displayed validation messages using React Testing Library's query methods.

Can I use other testing libraries with Formik?

Yes, you can use other libraries like Enzyme, but React Testing Library is recommended for its simplicity and focus on testing user interactions.

Frequently Asked Questions

Why is my form submission test failing?

Check if the form fields have the correct ids and if the onSubmit function is properly set up and connected.

How do I test form validation errors?

Simulate form input with invalid data and check for displayed validation messages using React Testing Library's query methods.

Can I use other testing libraries with Formik?

Yes, you can use other libraries like Enzyme, but React Testing Library is recommended for its simplicity and focus on testing user interactions.