How to implement drag and drop in cypress test?

后端 未结 6 1385
青春惊慌失措
青春惊慌失措 2020-12-14 07:47

I am struggling to test drag and drop with Cypress and Angular Material Drag and Drop. So the goal is to move \"Get to work\" from Todo to Done. I have created the following

6条回答
  •  隐瞒了意图╮
    2020-12-14 08:14

    Not Angular specific, but should be generic and simple enough to tweak if needed. I did try a lot of recipes out there and also cypress-file-upload but that wouldn't work with webp for example.

    The command below seems to work for most cases and reflects pretty closely what a user would do

    Cypress.Commands.add('dropFile', {prevSubject: true}, (subject, fileName, fileType) => {
      return cy.fixture(fileName, 'binary').then((data) => {
        return Cypress.Blob.binaryStringToBlob(data, fileType).then(blob => {
          const file = new File([blob], fileName, {type: fileType});
          const dataTransfer = new DataTransfer();
          dataTransfer.items.add(file);
          cy.wrap(subject)
            .trigger("dragenter", {force: true})
            .trigger("drop", {dataTransfer})
        })
      })
    })
    

    Ensure fixturesFolder is specified in your cypress.json config file. Then you simply use like below

    cy.get("#dropzone").dropFile("myfile1.webp", "image/webp")
    cy.get("#dropzone").dropFile("myfile2.jpg", "image/jpeg")
    

提交回复
热议问题