Description:
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).
Code:
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.