【问题标题】:react testing library, trying to test useForm validation messagesreact 测试库,尝试测试 useForm 验证消息
【发布时间】:2022-11-01 18:23:47
【问题描述】:

我正在尝试为我的表单验证编写 RTL 测试。我在验证中使用useFormYup 挂钩。

我要测试的场景是当用户单击Add 按钮提交来自而不填写所有必填字段(标题和描述)时。在这种情况下,一些错误消息将在 from 的空输入下弹出。我想来回测试这些消息。

我已经编写了测试,在那里我找到了标题、描述和添加按钮,但是当我单击添加按钮并执行screen.debug() 时,错误消息不存在。

表单输入被剪断:

  <div className="Form__title">
    <label className="Form__title--label" htmlFor="title">
      Title
    </label>
    <input
      {...register("title")}
      type="text"
      placeholder="Title..."
      data-testid="titleInput"
    />
    {errors?.title && (
      <p data-testid="titleError">{errors.title.message}</p>
    )}
  </div>

我的测试:

test("throws title must be at least 1 characters", async () => {
  renderWithProviders(<TileForm />);

  const error = "title must be at least 1 characters";

  const addNewIdeaButton = screen.getByText("Add New Idea");
  await userEvent.click(addNewIdeaButton);
  const descriptionInput = screen.getByTestId("descriptionInput");
  await userEvent.type(descriptionInput, "foo");
  const addButton = screen.getByText("Add");
  await userEvent.click(addButton);

  screen.debug();

  expect(screen.getByTestId("titleError")).toBeInTheDocument();
  // expect(screen.getByTestId("titleError")).toHaveValue(error);
});

不确定我错过了什么,似乎当我单击按钮时它没有提交表单,因此为什么没有显示错误消息。

我要测试的是这些红色消息:

【问题讨论】:

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


    【解决方案1】:

    对于任何面临此类或类似问题的人,问题是这样的:

    当您提交表单时,它是一个异步调用,并且需要一些时间才能弹出验证错误。

    要解决此问题,您需要将您的期望包装在 waitFor 中。它将等待预期的项目出现在 DOM 中,然后再断言它

      await waitFor(async () => {
        expect(await screen.findByText(titleError)).toHaveTextContent(
          titleError
        );
      });
    

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 1970-01-01
      • 2022-07-25
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2019-04-07
      • 2021-07-03
      相关资源
      最近更新 更多