【问题标题】:Pressing enter to submit form in react-testing-library does not work在 react-testing-library 中按 Enter 提交表单不起作用
【发布时间】:2020-04-09 06:45:08
【问题描述】:

说明:

我正在尝试测试当用户按下“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,所需的代码量最少。

【问题讨论】:

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


    【解决方案1】:

    以下内容对我有用:

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

    【讨论】:

      【解决方案2】:

      您可以通过按钮提交,但事件目标将是按钮而不是表单。要解决这个问题:

      • 提交表格
      • 在表单上使用引用
      • 表单上的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】:

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

      import { fireEvent } from '@testing-library/react-native'
      
      const input = getByTestId('input');
      fireEvent.focus(input);
      fireEvent.changeText(input, 'hello world')
      fireEvent.submitEditing(input);
      

      【讨论】:

        【解决方案4】:

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

        fireEvent.submit(input);
        

        【讨论】:

          猜你喜欢
          • 2021-04-10
          • 2020-10-27
          • 1970-01-01
          • 2020-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多