【发布时间】:2022-11-01 18:23:47
【问题描述】:
我正在尝试为我的表单验证编写 RTL 测试。我在验证中使用useForm 和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>
我的测试:
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