【问题标题】:Testing react-hook-forms submition fails [duplicate]测试react-hook-forms提交失败[重复]
【发布时间】:2021-11-23 16:46:02
【问题描述】:

我正在尝试做一些非常简单的事情,当我提交表单时,会调用传递给组件的函数 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 仅在表单有效时才调用回调。但我的表格没有任何限制:(

【问题讨论】:

    标签: reactjs react-testing-library react-hook-form


    【解决方案1】:

    经过一番挖掘,我找到了这个答案https://stackoverflow.com/a/69706522/7087543

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 2014-02-24
      • 2019-05-19
      • 1970-01-01
      • 2020-02-10
      相关资源
      最近更新 更多