In my react application I have a form with a dropdown select. Depending on the selected Option different inputs are rendered.
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} />
The TemplateFormSwitch
returns different form-components depending on the selected templateType
.
I'm using react-hook-form with FormProvider
and useFormContext
because my form is split up over multiple components/files.
I tried to write a Cypress-Test, by first clicking the select and then clicking on the desired option:
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");
Then when I try to submit my form all textfields get validated correctly. But somehow the select
with the templateType
doesn't validate and the submit action gets blocked.
Weirdly when I click manually in the application everything works fine and the templateType select gets validated correctly.
What do I need to do/change in order to test the MUI select correctly and trigger the react-hook-form validation accordingly, like I would if I test manually?
Here is a simple Demo-Project showing this behaviour
CodePudding user response:
Sometimes the javascript code use by commands is not enough to trigger validation checks.
The user will focus and blur each field, so you can also do that
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
});