skip to Main Content

I am using react-dropzone library to handle uploading image files. Now I would like to test this upload behaviour. The tests are written using cypress and I am using cypress-file-upload. Here’s my component

I tried to follow this example (https://gist.github.com/ZwaarContrast/00101934954980bcaa4ae70ac9930c60) as well, but didn’t get it to work .

    <ReactDropzone
      onDrop={onDrop}
      multiple={false}
      noDrag
      data-cy="uploadFile"
    >
      <button className={styles.avatarButton}>
        Upload Profile Picture
      </button>
    </ReactDropzone>
function onDrop(event) {
  const file = event[0];
  //openModal;
}

In my test I’m trying to test if the modal opens up, but the modal doesn’t open up in my case.

  cy.fixture('avatar.png', 'base64').then(fileContent => {
  cy.get('[data-cy="uploadFile"]').attachFile({
     fileContent: fileContent,
     fileName: 'avatar.png',
    });
  });   
  cy.get('[data-cy="uploadFile"]')
  .find('input').trigger('change', {force:true})  
  });

I’m not sure what I’m doing wrong here. I don’t see any modal on file upload. Any help would be appreciated.

2

Answers


  1. When using .attachFile with a drag’n’drop component, you have to specify it as the subjectType.
    From the docs:

    cy.get('[data-cy="dropzone"]')
      .attachFile('myfixture.json', { subjectType: 'drag-n-drop' });
    

    In your specific case, it would just be adding the additional options object.

    cy.get('[data-cy="uploadFile"]').attachFile({
         fileContent: fileContent,
         fileName: 'avatar.png',
        }, { 
         subjectType: 'drag-n-drop' 
        });
      });  
    
    Login or Signup to reply.
  2. Please see Cypress Component Test does not render react Component

    You can’t add data-id attributes directly to the the React component and have it appear on the DOM content.

    so <ReactDropzone ... data-cy="uploadFile"> does not work.

    Try instead adding data-cy="uploadFile" to the inner element (in your snippet it’s <button>)

    I’m not sure of the exact React code you have, since the piece you show does not run, but to get the <input> element you can use Cypress .closest() query to find the associated input.

    cy.fixture('avatar.png', 'base64').then(fileContent => {
      cy.get('[data-cy="uploadFile"]')
       .closest('input')                // nearest input to <button>
       .attachFile({
          fileContent: fileContent,
          fileName: 'avatar.png',
        });
      });   
      cy.get('[data-cy="uploadFile"]')
        .find('input').trigger('change', {force:true})  
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search