Problem: I am trying to upload an image with .selectFile
, but I am encountering an error that it is hidden, and thus it is not possible.
React Code With 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 Component:
<label role="button" datacy="uploadImage">
<input type="file" accept="image/png, image/jpeg" hidden="">
Change
</label>
Failed Attempts:
cy.get('[datacy="uploadImage"] input').selectFile("cypress/fixtures/Headshot 2.jpg");
Timed out retrying after 4000ms: cy.selectFile() failed because this element is not visible: This element is not visible because it has CSS property: display: none Fix this problem, or use {force: true} to disable error checking.
cy.get("input[type='file'] hidden").selectFile("cypress/fixtures/Headshot 2.jpg");
Timed out retrying after 4000ms: Expected to find element: input[type='file'] hidden, but never found it.
Question: What Cypress front-end test can I write that clicks the component and uploads an image?
You should just be able to target the <label>
element, since <input>
is within the .selectFile()
command is smart enough to find the input.
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
Tested with
<label role="button" datacy="uploadImage">
<input type="file" accept="image/png, image/jpeg" hidden="">
Change
</label>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With