【发布时间】:2020-07-06 20:17:50
【问题描述】:
我正在编写一个满足以下业务规则的测试:
如果我们从国家下拉列表中选择
Canada,如果省和邮政编码字段为空,则在模糊中显示错误消息。
我正在测试的 React 最终形式是:
<Form
onSubmit={onSubmit}
validate={values => {
const errors: ValidationErrors = {};
if (!values.country) {
errors.country = "Country must be selected";
}
if (values.country === "Canada" && !values.province) {
errors.province = "Province must be provided";
}
if (values.country === "Canada" && !values.postalCode) {
errors.postalCode = "Postal code must be provided";
}
return errors;
}}
render={({
...
}) => (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="country">Country</label>
<br />
<Field<string> id="country" name="country" component="select">
<option />
<option value="Canada">Canada</option>
<option value="US">US</option>
</Field>
</div>
<Condition when="country" is="Canada">
<div>
<label htmlFor="province">Province</label>
<br />
<Field id="province" name="province" component="input" />
<Error name="province" />
</div>
<div>
<label htmlFor="postalCode">Postal Code</label>
<br />
<Field id="postalCode" name="postalCode" component="input" />
<Error name="postalCode" />
</div>
</Condition>
...
</form>
)}
我写的测试是这样的:
describe("Contact form", () => {
test("should show errors if Canada is seledted but province and postal code are blank", async () => {
const { getByLabelText, findByRole } = render(<ContactForm />);
fireEvent.change(getByLabelText("Country"), {
target: { value: "Canada" }
});
fireEvent.change(getByLabelText("Province"), {
target: { value: "" }
});
fireEvent.change(getByLabelText("Postal Code"), {
target: { value: "" }
});
fireEvent.blur(getByLabelText("Postal Code"));
const postalAlert = await findByRole("alert", {
name: "Postal code must be provided"
});
expect(postalAlert).toBeInTheDocument();
const provinceAlert = await findByRole("alert", {
name: "Province must be provided"
});
expect(provinceAlert).toBeInTheDocument();
我正在尝试触发错误消息 - 使用 role="alert" 呈现出来 - 但我的测试失败:Unable to find role="alert"
现在,如果我删除我试图过滤的 name 属性,则找到 alert:
const postalAlert = await findByRole("alert"); // SUCCESS
我可以使用findAllByRole 检索警报并对其进行迭代,但我真的只想用可访问的名称显式查询每个警报并断言它们在文档中。
我在调试屏幕的时候看到了元素,我只是想弄清楚如何直接用它的角色和名称来查询它:
<span
role="alert"
style="color: rgb(153, 0, 0);"
>
Postal code must be provided
</span>
示例表格:https://codesandbox.io/s/react-ts-unit-test-example-6scjc?file=/src/ContactForm.test.tsx
【问题讨论】:
标签: reactjs react-testing-library react-final-form final-form testing-library