Using a mock function in Jest

We are going to make another improvement to the test that verified that submitting the Contact Us form without filling in the fields results in errors being displayed on the page. We are going to add an additional check, to make sure the submit handler is not executed:

  1. Let's go back to the first component test we wrote: ContactUs.test.tsx. We manually created a handleSubmit function that we referenced in our instance of the ContactUs component. Let's change this to a Jest mock function:
const handleSubmit = jest.fn();

Our test will run correctly, as it did before, but this time Jest is mocking the function for us.

  1. Now that Jest is mocking the submit handler, we can check whether it was called as an additional check at the end of our test. We do this using the not and toBeCalled Jest matcher functions:
const errorSpans = container.querySelectorAll(".form-error");
expect(errorSpans.length).toBe(2);

expect(handleSubmit).not.toBeCalled();

This is really nice, because we've not only simplified our submit handler function, but we've also really easily added a check to verify that it hasn't been called.

Let's move on to the second test we implemented, which verified that a valid Contact Us form was submitted okay:

  1. We'll again change the handleSubmit variable to reference a Jest mock function:
const handleSubmit = jest.fn();
  1. Let's verify that the submit handler is called. We do this using the toBeCalledTimes Jest function to pass in the number of times we expect the function to be called, which is 1 in our case:
const errorsDiv = container.querySelector("[data-testid='formErrors']");
expect(errorsDiv).toBeNull();

expect(handleSubmit).toBeCalledTimes(1);

  When the test executes, it should still pass. 

  1. There is one other useful check we can do. We know that the submit handler is being called, but does it have the correct arguments? We can use the toBeCalledWith Jest function to check this:
expect(handleSubmit).toBeCalledTimes(1);
expect(handleSubmit).toBeCalledWith({
name: "Carl",
email: "[email protected]",
reason: "Support",
notes: ""
});

  Again, when the test executes, it should still pass. 

So, by letting Jest mock our submit handler, we've quickly added a few valuable additional checks to our tests.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.30.253