Reputation: 11
I am new in Jest and React Testing Library and want to test my Form created with Formik and Yup. The test should test when the User inputs invalid values, that the Submit Button should be disabled.
I tried using toBeDisabled() and the Test was succesful. I was a little skeptic that my Test did pass on the first try and tried out to checked if it fails when I use the Custom Matcher .toBeEnabled(), which also passed the test. Then I tried not.toBeDisabled() and the test failed which is correct. My Question is why did .toBeEnabled() pass the test while not.toBeDisabled() correctly fails the test with the given invalid Values.
Here is the Code for failing the Test:
test("Submit is disabled, when User has not given any valid value", async () => {
const handleSubmit = jest.fn();
render(<Reservations onSubmit={handleSubmit} />);
const firstNameField = screen.getByLabelText(/First Name/i);
const lastNameField = screen.getByLabelText(/Last Name/i);
const emailField = screen.getByLabelText(/Email/i);
const dateField = screen.getByLabelText(/Choose date/i);
const occasionField = screen.getByLabelText(/Occasion/i);
const guestField = screen.getByLabelText(/Number of guests/i);
// Fill out the form with sample data
fireEvent.change(firstNameField, {
target: { value: "S" },
});
fireEvent.focus(firstNameField);
fireEvent.blur(firstNameField);
fireEvent.change(lastNameField, {
target: { value: "S" },
});
fireEvent.focus(lastNameField);
fireEvent.blur(lastNameField);
fireEvent.change(emailField, {
target: { value: "S@s" },
});
fireEvent.focus(emailField);
fireEvent.blur(emailField);
fireEvent.change(dateField, {
target: { value: "2024-12-12" },
});
fireEvent.focus(dateField);
fireEvent.blur(dateField);
fireEvent.change(occasionField, {
target: { value: "default" },
});
fireEvent.focus(occasionField);
fireEvent.blur(occasionField);
fireEvent.change(guestField, {
target: { value: -1 },
});
fireEvent.focus(guestField);
fireEvent.blur(guestField);
const submitButton = screen.getByRole("button", { name: /Submit/i });
// Ensure the submit button is disabled
expect(submitButton).not.toBeDisabled();
});
And if i replace not.toBeDisabled with toBeEnabled() it passes the test.
// Ensure the submit button is disabled
expect(submitButton).toBeEnabled();
});
I expected that with the custom Matcher from Jest Dom the .toBeEnabled to fail the test which it did not.
Upvotes: 1
Views: 36