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?