Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Click On A Hidden Input In Cypress With MUI and Upload An Image?

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:

  1. 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.

  2. 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?

like image 828
Luke Avatar asked Sep 06 '25 03:09

Luke


1 Answers

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>
like image 99
Fody Avatar answered Sep 09 '25 00:09

Fody