Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: "[email protected]"
    },
    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: "[email protected]" } });
    });

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

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

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

like image 950
coderpc Avatar asked Jun 25 '26 15:06

coderpc


1 Answers

You should use jest.mock:

const setFieldValue = jest.fn();
const handleSubmit = jest.fn();
jest.mock('formik', () => ({
  useFormik: () => ({
    setFieldValue,
    handleSubmit,
    values: {
      transferMethodCountry: 'AZ',
      transferMethodCurrency: 'AZN',
      type: 'BANK_ACCOUNT',
    },
  }),
}));

and except(handleSubmit).toBeCalled()

like image 86
Nagibaba Avatar answered Jun 28 '26 05:06

Nagibaba