[英]React MUI Select with react-hook-form doesn't work with Cypress
在我的反应应用程序中,我有一个带有下拉选择的表单。 根据选定的选项,呈现不同的输入。
const [templateType, setTemplateType] = useState("");
const {
register,
formState: { errors },
setValue,
} = useFormContext();
...
<FormControl>
<InputLabel>Template Typ</InputLabel>
<Select id="SelectTemplateType"
className="custom-input"
{...register("templateType", { required: true })}
label="Template Typ"
value={templateType}
onChange={(e) => setTemplateType(e.target.value)}
error={errors.templateType}
>
{TEMPLATE_TYPES.map((option) => (
<MenuItem value={option.value}>{option.label}</MenuItem>
))}
</Select>
{errors.templateType && (
<FormHelperText sx={{ color: "#d32f2f" }}>
Eintrag darf nicht leer sein!
</FormHelperText>
)}
</FormControl>
<TemplateFormSwitch templateType={templateType} />
TemplateFormSwitch 根据所选模板类型返回不同的表单组件。
我将 react-hook-form 与 FormProvider 和 useFormContext 一起使用,因为我的表单被拆分为多个组件/文件。
我尝试编写赛普拉斯测试,首先单击选择,然后单击所需的选项:
cy.get('#SelectTemplateType').click({ force: true })
cy.get('[data-value="Text"]').click({ force: true });
//Entering Test values to TextFields
cy.get('#mui-1').type("Test");
cy.get('#mui-2').type("HelloWorld");
然后,当我尝试提交表单时,所有文本字段都会得到正确验证。 但不知何故,带有模板类型的选择没有验证,提交操作被阻止。
奇怪的是,当我在应用程序中手动单击时,一切正常,并且模板类型选择得到正确验证。
为了正确测试 MUI 选择并相应地触发 react-hook-form 验证,我需要做什么/更改,就像我手动测试一样?
有时,命令使用的 javascript 代码不足以触发验证检查。
用户将聚焦并模糊每个字段,因此您也可以这样做
it("form test", () => {
cy.visit("http://localhost:3000");
cy.get('[href="/form"] > .MuiListItem-root > .MuiListItemButton-root')
.click();
cy.get("#SelectGenderType").click();
cy.get('[data-value="m"]').click()
cy.get("#SelectGenderType").focus().blur()
cy.get("form > :nth-child(1) > :nth-child(2)").type("Max");
cy.get("form > :nth-child(1) > :nth-child(3)").type("Mustermann");
cy.get(".MuiButton-root")
.click();
cy.contains('p', 'Field cannot be empty!').should('not.exist') // ✅ passes
});
我克隆了你的回购并运行了测试,但对我来说没有产生任何错误。 我运行了确切的脚本。
describe('my test spec', () => {
it('form test', () => {
cy.visit('http://localhost:3000')
cy.get(
'[href="/form"] > .MuiListItem-root > .MuiListItemButton-root'
).click()
cy.get('#SelectGenderType').click()
cy.get('[data-value="m"]').click()
cy.get('form > :nth-child(1) > :nth-child(2)').type('Max')
cy.get('form > :nth-child(1) > :nth-child(3)').type('Mustermann')
cy.get('.MuiButton-root').click()
})
})
测试运行器截图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.