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

Posted

技术标签:

【中文标题】在 react-testing-library 中按 Enter 提交表单不起作用【英文标题】:Pressing enter to submit form in react-testing-library does not work 【发布时间】: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,所需的代码量最少。

【问题讨论】:

【参考方案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, "abcenter");

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

【讨论】:

仅供参考,my-form 不是有效的 ARIA 角色。请确保使用有效的 ARIA 角色。在这种情况下,只需role="form"。更多信息developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles【参考方案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);

【讨论】:

以上是关于在 react-testing-library 中按 Enter 提交表单不起作用的主要内容,如果未能解决你的问题,请参考以下文章

ubuntu中怎样安装雅黑字体

ubuntu安装过程中调出终端

怎么在ubuntu 进入System

如何在ubuntu中删除/卸载自行安装的字体

ubuntu终端中字体颜色含义

怎样在 Ubuntu 中修改默认程序