如何让 React 测试库用户事件输入到输入中

How to get React Testing Library's userEvent to type into an input

我可以使用 React 测试库的 fireEvent 方法成功实施测试,但是当我尝试使用 userEvent 进行等效测试时,我无法让它触发任何东西。我该如何解决这个问题?

CodeSandbox

/MyInput.tsx

import { useState } from "react";

export default function MyInput() {
  const [inputTextState, setInputTextState] = useState("");
  return (
    <div>
      <label>
        My Input
        <input
          value={inputTextState}
          onChange={(event) => setInputTextState(event.target.value)}
        />
      </label>
      <p>{inputTextState}</p>
    </div>
  );
}

__tests__/MyInput.test.tsx

import { fireEvent, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import MyInput from "../MyInput";

const setup = () => {
  const utils = render(<MyInput />);
  const input = utils.getByLabelText("My Input") as HTMLInputElement;
  return {
    input,
    ...utils
  };
};

test("Simply input a number with fireEvent", () => {
  const { input } = setup();
  fireEvent.change(input, { target: { value: "23" } });
  expect(input.value).toBe("23");
});

test("Try userEvent", () => {
  const { input } = setup();
  userEvent.type(input, "23");
  expect(input.value).toBe("23");
});

只是我需要添加 async 和 await:

test("Try userEvent", async () => {
  const { input } = setup();
  await userEvent.type(input, "23");
  expect(input.value).toBe("23");
});

v13@testing-library/user-event 没有 return 承诺,但 v14 的更新做到了。目前,create-react-app 提供v13,因此与最新文档不匹配。外行人很困惑!