Drag and drop file upload lets users add files by dragging them into a box. Testing this ensures the upload works smoothly and files are accepted correctly.
0
0
Drag and drop file upload in Cypress
Introduction
Testing a website where users can drag files to upload, like profile pictures or documents.
Checking that the drag and drop area accepts only allowed file types.
Verifying that the file upload triggers the right response after dropping a file.
Ensuring error messages show if a wrong file is dropped.
Automating tests for drag and drop upload to save manual effort.
Syntax
Cypress
cy.get('selector').attachFile('filename', { subjectType: 'drag-n-drop' })
Use the attachFile command from the cypress-file-upload plugin.
The subjectType: 'drag-n-drop' option simulates dragging and dropping the file.
Examples
This drags and drops
example.pdf into the element with ID upload-area.Cypress
cy.get('#upload-area').attachFile('example.pdf', { subjectType: 'drag-n-drop' })
Simulates dropping
image.png into an element with class dropzone.Cypress
cy.get('.dropzone').attachFile('image.png', { subjectType: 'drag-n-drop' })
Sample Program
This test visits a page with a drag and drop upload area, drops testfile.txt into it, and checks for a success message.
Cypress
describe('Drag and Drop File Upload Test', () => { it('uploads a file by drag and drop', () => { cy.visit('https://example.com/upload') cy.get('#drag-drop-area').attachFile('testfile.txt', { subjectType: 'drag-n-drop' }) cy.get('#upload-success').should('contain.text', 'Upload complete') }) })
OutputSuccess
Important Notes
Install cypress-file-upload plugin before using attachFile.
Place test files in the cypress/fixtures folder for easy access.
Use clear and stable selectors for the drag and drop area to avoid flaky tests.
Summary
Drag and drop file upload tests check if files can be added by dragging into a box.
Use attachFile with subjectType: 'drag-n-drop' to simulate this in Cypress.
Verify success or error messages after the file is dropped to confirm correct behavior.