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

Solution 1:

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);

Solution 2:

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();
});

Solution 3:

You can submit by button but the event target will be the button and not the form. To resolve this:

  • submit the form
  • useRef on the form
  • ByTestId on the form

Submitting the form is only accessible if it has an accessible name. In this sense, using role="my-form" (ByRole) or aria-label="form's purpose" (ByLabelText or ByRole("form")).

import "@testing-library/jest-dom/extend-expect";
import { getByRole, fireEvent } from '@testing-library/dom';

test("test form", () => {
  const div = document.createElement("div");

  div.innerHTML = `
  <form role="my-form">
    <label for="first_name">
      First Name:
      <input id="first_name" type="text" />
    </label>
    <button type="submit">Submit</button>
  </form>
  `;

  const handleSubmit = jest.fn();
  div.querySelector('form').onsubmit = handleSubmit;

  fireEvent.submit(getByRole(div, "my-form"));
  expect(handleSubmit).toHaveBeenCalledTimes(1);
});