在 react-testing-library 中按 Enter 提交表单不起作用

jay*_*pee 12 forms events reactjs jestjs react-testing-library

描述:

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();
});
Run Code Online (Sandbox Code Playgroud)

Here is a CodeSandbox with the minimal amount of code needed.

Pet*_*nas 18

以下对我有用:

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();
});
Run Code Online (Sandbox Code Playgroud)


小智 6

不太清楚交互的来源是什么,但submit可以调用input它,它似乎修复了沙箱中的测试:

fireEvent.submit(input);
Run Code Online (Sandbox Code Playgroud)

  • 作者声明“我正在尝试测试当用户按下“Enter”键时表单是否提交。”。您的答案不会模拟该行为。 (7认同)