I am trying to test that a form submits when the user presses the "Enter" key. I have a passing test for when pressing the Submit
button, but I also want to be sure the form submits with the keyboard (convenience and a11y).
test("should submit when pressing enter", () => {
const handleSubmit = jest.fn();
const { getByLabelText } = render(<App handleSubmit={handleSubmit} />);
const input = getByLabelText("Name:");
fireEvent.change(input, { target: { value: "abc" } });
fireEvent.keyPress(input, { key: "Enter", code: 13, charCode: 13 });
expect(handleSubmit).toHaveBeenCalled();
});
Here is a CodeSandbox with the minimal amount of code needed.
To submit a form using the Enter key in React: Add a button element with type set to submit . Add an onSubmit prop that points to a submit handler function. Every time the user presses Enter, the handle submit function will be invoked.
To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() . The preventDefault method prevents the browser from refreshing the page when the form is submitted.
React Testing Library is a testing utility tool that's built to test the actual DOM tree rendered by React on the browser. The goal of the library is to help you write tests that resemble how a user would use your application.
It's a little less clear what the source of the interaction is intended to be, but submit
can be called on the input
and it appears to fix the test in the sandbox:
fireEvent.submit(input);
The following worked for me:
import userEvent from "@testing-library/user-event";
import { render } from "@testing-library/react";
test("should submit when pressing enter", () => {
const handleSubmit = jest.fn();
const { getByLabelText } = render(<App handleSubmit={handleSubmit} />);
const input = getByLabelText("Name:");
userEvent.type(input, "abc{enter}");
expect(handleSubmit).toHaveBeenCalled();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With