Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

442
Views
Test useFormik hook with React Testing Library

I did a thorough search before positing this question, most of them were using <Formik/> where they had sent onSubmit handler as a prop so that it can be tested whether it is called or not when the form is submitted.

In my case, I'm using useFormik hook for my form and I can't get to reach the onSubmit code when the form is submitted. The type property of button is submit so the onClick function is undefined when I displayed the element in console log.

Below is excerpt from my code

Component

export const WithMaterialUI = () => {
  const formik = useFormik({
    initialValues: {
      email: "foobar@example.com"
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2));
    }
  });

  return (
    <div>
      <form onSubmit={formik.handleSubmit} data-testid="form">
        <TextField
          data-testid="email"
          fullWidth
          id="email"
          name="email"
          label="Email"
          value={formik.values.email}
          onChange={formik.handleChange}
          error={formik.touched.email && Boolean(formik.errors.email)}
          helperText={formik.touched.email && formik.errors.email}
        />
        <Button color="primary" variant="contained" fullWidth type="submit">
          Submit
        </Button>
      </form>
    </div>
  );
};

Test case

const mockSubmit = jest.fn();

describe("Test for formik onSubmit", () => {
  it("should handle form submission", async () => {
    const { getByTestId } = render(<WithMaterialUI />);

    const email = getByTestId("email");
    const form = getByTestId("form");

    act(() => {
      fireEvent.change(email, { target: { value: "abc@gmail.com" } });
    });

    act(() => {
      fireEvent.submit(form);
    });

    await waitFor(() => {
      expect(mockSubmit).toHaveBeenCalled();
    });
  });
});

I created a working example using CodeSandbox. Could anyone please help?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!