0
0
Cypresstesting~15 mins

Drag and drop file upload in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify drag and drop file upload functionality
Preconditions (2)
Step 1: Locate the drag and drop upload area on the page
Step 2: Drag the file 'sample.txt' from fixtures and drop it onto the upload area
Step 3: Wait for the file to be processed and uploaded
Step 4: Verify that the file name 'sample.txt' appears in the uploaded files list
✅ Expected Result: The file 'sample.txt' is successfully uploaded and listed on the page after drag and drop
Automation Requirements - Cypress
Assertions Needed:
Verify the drag and drop area is visible
Verify the file is uploaded and listed with correct file name
Best Practices:
Use cy.fixture() to load test file
Use cypress-file-upload plugin for drag and drop simulation
Use explicit assertions with cy.get().should()
Avoid hardcoded waits; use Cypress built-in retries
Automated Solution
Cypress
import 'cypress-file-upload';

describe('Drag and Drop File Upload Test', () => {
  beforeEach(() => {
    cy.visit('/file-upload');
  });

  it('should upload a file via drag and drop', () => {
    const fileName = 'sample.txt';
    cy.get('#drag-drop-area').should('be.visible');

    cy.fixture(fileName).then(fileContent => {
      cy.get('#drag-drop-area').attachFile({
        fileContent,
        fileName,
        mimeType: 'text/plain',
        encoding: 'utf8'
      }, { subjectType: 'drag-n-drop' });
    });

    cy.get('#uploaded-files').should('contain.text', fileName);
  });
});

The test starts by visiting the file upload page.

We check that the drag and drop area is visible to ensure the page loaded correctly.

Using cy.fixture(), we load the test file sample.txt from the fixtures folder.

We then use the attachFile command from the cypress-file-upload plugin to simulate dragging and dropping the file onto the upload area.

Finally, we assert that the uploaded files list contains the file name, confirming the upload succeeded.

This approach uses explicit assertions and avoids hardcoded waits, relying on Cypress's automatic retries for stability.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not importing or configuring the cypress-file-upload plugin', 'why_bad': "Without the plugin, the drag and drop simulation won't work, causing the test to fail.", 'correct_approach': "Import 'cypress-file-upload' in the test file or support file before using attachFile."}
Using hardcoded waits like cy.wait(5000)
{'mistake': 'Using incorrect selector for drag and drop area', 'why_bad': "If the selector is wrong, the test won't find the element and will fail.", 'correct_approach': 'Use stable selectors like IDs or data attributes that are unlikely to change.'}
Bonus Challenge

Now add data-driven testing with 3 different files: 'sample.txt', 'image.png', and 'document.pdf' to verify drag and drop upload for multiple file types.

Show Hint