Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pressing enter to submit form in react-testing-library does not work

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.

like image 927
jaypee Avatar asked Dec 16 '19 19:12

jaypee


People also ask

How do you use Enter to submit a form React?

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.

How do you prevent Enter key submitting form in React?

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.

How does React testing library work?

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.


Video Answer


2 Answers

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);
like image 84
Kevin Gorski Avatar answered Sep 17 '22 14:09

Kevin Gorski


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();
});
like image 24
Peter Cardenas Avatar answered Sep 18 '22 14:09

Peter Cardenas