提问人:Luke 提问时间:2/10/2023 最后编辑:Kitty.FlanaganLuke 更新时间:2/27/2023 访问量:621
如何使用 MUI 单击赛普拉斯中的隐藏输入并上传图像?
How Do I Click On A Hidden Input In Cypress With MUI and Upload An Image?
问:
问题:我正在尝试上传带有 的图像,但是我遇到了隐藏图像的错误,因此无法。.selectFile
使用 Material UI 的 React 代码:
<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>
失败的尝试:
cy.get('[datacy="uploadImage"] input').selectFile("cypress/fixtures/Headshot 2.jpg");
4000 毫秒后重试超时:cy.selectFile() 失败,因为此元素不可见: 此元素不可见,因为它具有 CSS 属性:display: none 修复此问题,或使用 {force: true} 禁用错误检查。
cy.get("input[type='file'] hidden").selectFile("cypress/fixtures/Headshot 2.jpg");
4000 毫秒后重试超时:预计会发现 element: input[type='file'] 隐藏,但从未找到它。
问题:我可以编写什么 Cypress 前端测试来单击组件并上传图像?
答:
正如 Cypress 文档中所说,需要使用 prop。.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
您应该能够定位元素,因为在命令中足够智能,可以找到输入。<label>
<input>
.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>
评论