簡體   English   中英

帶有 react-hook-form 的 React MUI Select 不適用於賽普拉斯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM