按Enter键在反应测试库中提交表单不起作用

时间:2019-12-16 19:02:18

标签: reactjs forms events jestjs react-testing-library

说明:

我正在尝试测试用户按下“ Enter”键时是否提交了表单。按下Submit按钮时,我通过了一项测试,但是我也想确保表单是通过键盘提交的(便利和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();
});

这里是CodeSandbox,代码量最少。

4 个答案:

答案 0 :(得分:4)

尚不清楚交互的源是什么,但是可以在submit上调用input,并且似乎可以在沙盒中修复该测试:

fireEvent.submit(input);

答案 1 :(得分:0)

要模拟键盘显示/隐藏,我首先关注输入,然后模拟打字。这样,您可以触发onSubmitEditing事件来模拟键盘上按下的“提交”按钮。

import { fireEvent } from '@testing-library/react-native'

const input = getByTestId('input');
fireEvent.focus(input);
fireEvent.changeText(input, 'hello world')
fireEvent.submitEditing(input);

答案 2 :(得分:0)

您可以按按钮提交,但事件目标将是按钮而不是表单。解决此问题的方法:

  • 提交表格
  • 表格上的useRef
  • 在表单上按ByTestId

只有具有accessible name的表单才能访问。从这种意义上讲,使用role="my-form"(ByRole)或aria-label="form's purpose"(ByLabelText或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);
});

答案 3 :(得分:0)

以下对我有用:

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