测试 react-hook-forms 提交失败

Testing react-hook-forms submition fails

我正在尝试做一些非常简单的事情,当我提交表单时,将调用传递给组件的函数 prop。如果我 运行 应用程序,这是有效的,但是当我 运行 单元测试时,它总是失败。

expect(myFunction).toHaveBeenCalledWith(...expected) 
Expected: "New Reason 1" 
Number of calls: 0

这是测试:

describe("New Reason Form", () => {
  it("calls onCreate prop when the form is submitted", () => {
    const onCreate = jest.fn().mockName("onCreate");
    const { queryByTestId } = render(
      <NewReasonForm onCreate={onCreate} />
    );

    const submitButton = queryByTestId("submit");
    fireEvent.click(submitButton!);

    expect(onCreate).toHaveBeenCalledWith("New Reason 1");
  });
});

这是组件

export const NewReasonForm: React.FC<Props> = ({ onCreate }) => {
  const { register, handleSubmit } = useForm();
  const onSubmit = (data: any) => onCreate("New Reason 1");

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>Example</label>
      <input
        defaultValue="test"
        {...register("example")}
        data-testid="example"
      />

      <input type="submit" data-testid="submit" />
    </form>
  );
};

我已经花了 8 个多小时试图解决这个问题并在 google 中搜索,但看起来遇到这个问题的人已经放弃了。但是对我来说它看起来很基础,如果我不能测试这个简单的功能,我将如何测试更复杂的功能?

备注

当我删除 handleSubmit 时,它似乎可以工作,但理论上我不应该那样做。据我所见,handleSubmit 仅在表单有效时调用回调。但是我的表格没有任何限制:(

深入挖掘后我找到了这个答案

TL;DR;基本上 handleSubmit 是异步的,所以你只需要像这样用等待包装它

await waitFor(() => {
      expect(onCreate).toHaveBeenCalledWith("New Reason 1");
    });