简体   繁体   中英

React MUI Select with react-hook-form doesn't work with Cypress

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('#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");

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?

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
});

I cloned your Repo and ran the test, but for me there was no error that was produced. I ran the exact script.

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()
  })
})

Screenshot of the test runner:

测试运行器屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM