How to test react form onSubmit with formik and react testing library?

Viewed 1791

I'm learning how to test react form and I don't understand why my test does not success ?

    Expected: {"email": "john.dee@someemail.com", "firstName": "John", "lastName": "Dee", "password": "password"}

    Number of calls: 0

my form is simple:

const SignUpForm = () => {
  const formik = useFormik({
    initialValues: initialValues,
    validationSchema: schema,
    onSubmit: submitForm,
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="firstName">First Name</label>
      < input ..>
      <label htmlFor="lastName">Last Name</label>
      < input ..>
      <label htmlFor="password">password</label>
      < input ..>
      <label htmlFor="email">Email</label>
      < input ..>
      <button type="submit">Submit</button>
    </form>
  );
};

export default SignUpForm;

and the test:

test("rendering and submitting a basic Formik form", async () => {
  const handleSubmit = jest.fn();
  render(<SignUpForm onSubmit={handleSubmit} />);

  userEvent.type(screen.getByLabelText(/First Name/i), "John");
  userEvent.type(screen.getByLabelText(/Last Name/i), "Dee");
  userEvent.type(screen.getByLabelText(/Email/i), "john.dee@someemail.com");
  userEvent.type(screen.getByLabelText(/password/i), "password");

  userEvent.click(screen.getByRole("button", { name: /Submit/i }));

  await waitFor(() =>
    expect(handleSubmit).toHaveBeenCalledWith({
      email: "john.dee@someemail.com",
      firstName: "John",
      lastName: "Dee",
      password: "password",
    })
  );
});

I did export "initialValues", "schema" and "onsubmit" in others files, and when I do test myself all seems to be working properly.

In the console, when the test is done I can see my form with all values filled like:

 <input id="email" name="email" type="email" value="john.dee@someemail.com" />

update: here is a link with all relevant code: https://pastebin.com/CbpFFzf4

1 Answers

Your SignUpForm doesn't have an onSubmit prop.

If your onSubmit comes from another file, you should mock the function in that module.

import * as HelperFunctions from './submitForm.js'

At the start of your test, you can spy on that function.

jest.spyOn(HelperFunctions, 'onSubmit')

then you can test if it is being called like so.

expect(HelperFunctions.onSubmit).toHaveBeenCalledWith({
      email: "john.dee@someemail.com",
      firstName: "John",
      lastName: "Dee",
      password: "password",
    })

make sure the functions are exported.

Related