File testing checks if files upload and download correctly. This ensures users get the right files without errors.
0
0
Why file testing validates uploads and downloads in Cypress
Introduction
When a user uploads a profile picture to a website
When downloading a report from an online dashboard
When testing if a file attachment sends correctly in a form
When verifying that a downloaded invoice matches the original
When checking if a file upload triggers the right server response
Syntax
Cypress
cy.get('input[type=file]').attachFile('filename.ext') cy.downloadFile('url', 'folder', 'filename.ext') cy.readFile('path/to/file').should('have.length.greaterThan', 0)
Use attachFile to simulate file uploads in Cypress.
Use readFile to check if a file exists or has correct content after download.
Examples
This uploads a file named
example.pdf to a file input.Cypress
cy.get('input[type=file]').attachFile('example.pdf')
This checks that the downloaded file
example.pdf exists in the downloads folder.Cypress
cy.readFile('cypress/downloads/example.pdf').should('have.length.greaterThan', 0)
This verifies the downloaded file contains the word 'Invoice'.
Cypress
cy.readFile('cypress/downloads/example.pdf').should('include', 'Invoice')
Sample Program
This test uploads a file named testfile.txt and checks for a success message. Then it downloads the same file and verifies it exists and contains the text 'Hello Cypress'.
Cypress
describe('File Upload and Download Test', () => { it('uploads a file and verifies download', () => { cy.visit('/upload') cy.get('input[type=file]').attachFile('testfile.txt') cy.get('button#upload').click() cy.contains('Upload successful').should('be.visible') cy.visit('/download') cy.get('a#downloadFile').click() cy.readFile('cypress/downloads/testfile.txt').should('have.length.greaterThan', 0) cy.readFile('cypress/downloads/testfile.txt').should('include', 'Hello Cypress') }) })
OutputSuccess
Important Notes
Always clean up downloaded files after tests to avoid false positives.
Use descriptive file names to avoid confusion during tests.
Check file content, not just existence, to ensure correct downloads.
Summary
File testing ensures uploads and downloads work as expected.
It helps catch errors users might face with file handling.
Use Cypress commands like attachFile and readFile for testing files.