【问题标题】:How Do I Click On A Hidden Input In Cypress With MUI and Upload An Image?如何使用 MUI 在 Cypress 中单击隐藏输入并上传图像?
【发布时间】:2023-02-10 05:56:02
【问题描述】:

问题:我正在尝试使用 .selectFile 上传图片,但我遇到了一个错误,它被隐藏了,因此这是不可能的。

使用 Material UI 反应代码:

      <Button
        datacy="uploadImage"
        size={"medium"}
        disableRipple
        disableTouchRipple
        disableFocusRipple
        component="label"
        variant={"text"}
        sx={{ marginTop: { xs: 2, md: 0 }, p: 0, width: "fit-content" }}
      >
        <input
          type="file"
          onChange={(e) => onChange(e)}
          hidden
          accept="image/png, image/jpeg"
        />
        {hasProfilePicture ? "Change" : "Upload"}
      </Button>

HTML 组件:

<label role="button" datacy="uploadImage">
   <input type="file" accept="image/png, image/jpeg" hidden="">
   Change
</label>

失败的尝试:

  1. cy.get('[datacy="uploadImage"] input').selectFile("cypress/fixtures/Headshot 2.jpg");

    4000 毫秒后重试超时:cy.selectFile() 失败,因为此元素不可见: 该元素不可见,因为它具有 CSS 属性:display: none 修复此问题,或使用 {force: true} 禁用错误检查。

  2. cy.get("input[type='file'] hidden").selectFile("cypress/fixtures/Headshot 2.jpg");

    4000 毫秒后重试超时:预期会找到隐藏的元素:input[type='file'],但从未找到它。

    问题:我可以编写什么 Cypress 前端测试来单击组件并上传图像?

【问题讨论】:

    标签: reactjs cypress


    【解决方案1】:

    正如 Cypress 文档在 .selectFile 中所说,需要使用 force: true 道具。

    cy.get('[datacy="uploadImage"] input').selectFile("cypress/fixtures/Headshot 2.jpg", {force: true});

    文档:https://docs.cypress.io/api/commands/selectfile#On-a-hidden-input

    【讨论】:

      【解决方案2】:

      您应该能够定位 &lt;label&gt; 元素,因为 &lt;input&gt;.selectFile() 中,命令足够智能以找到输入。

      cy.get('[datacy="uploadImage"]')
        .selectFile("cypress/fixtures/example.png")
      
      cy.get('[datacy="uploadImage"] input')
        .its('0.files')
        .should('have.length', 1)      // passes
        .its('0.name')
        .should('eq', 'example.png')   // passes
      

      测试了

      <label role="button" datacy="uploadImage">
         <input type="file" accept="image/png, image/jpeg" hidden="">
         Change
      </label>
      

      【讨论】:

        猜你喜欢
        • 2019-03-31
        • 1970-01-01
        • 1970-01-01
        • 2019-01-06
        • 1970-01-01
        • 2022-06-22
        • 1970-01-01
        • 1970-01-01
        • 2020-05-19
        相关资源
        最近更新 更多