Joh*_*ohn 1 reactjs react-testing-library use-form
我正在尝试为表单上的验证编写 RTL 测试。我正在使用useFormhook 来Yup进行验证。
我想测试的场景是当用户单击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>
Run Code Online (Sandbox Code Playgroud)
我的测试:
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);
});
Run Code Online (Sandbox Code Playgroud)
不确定我缺少什么,似乎当我单击按钮时它没有提交表单,因此错误消息没有显示。
对于任何面临此类或类似问题的人来说,问题是:
当您提交表单时,这是一个异步调用,需要一些时间才能弹出验证错误。
要解决这个问题,您需要将您的期望包含在waitFor. 它将等待预期的项目出现在 DOM 中,然后再对其进行断言
await waitFor(async () => {
expect(await screen.findByText(titleError)).toHaveTextContent(
titleError
);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1938 次 |
| 最近记录: |