0
0
Cypresstesting~5 mins

File download verification in Cypress

Choose your learning style9 modes available
Introduction

We check if a file downloads correctly to make sure users get the right file without errors.

When testing a button that lets users download reports.
When verifying that invoices download after a purchase.
When checking if a user can download a PDF guide from a website.
When confirming that exported data files are saved correctly.
When ensuring that download links provide the correct file type.
Syntax
Cypress
cy.downloadFile(url, directory, filename)
cy.readFile(filepath)

cy.downloadFile is a custom command often added to Cypress for downloading files.

cy.readFile checks if the file exists and can be read in the specified folder.

Examples
Downloads a PDF report and checks if it exists in the downloads folder.
Cypress
cy.downloadFile('https://example.com/report.pdf', 'cypress/downloads', 'report.pdf')
cy.readFile('cypress/downloads/report.pdf')
Downloads a CSV file and verifies its presence.
Cypress
cy.downloadFile('https://example.com/data.csv', 'cypress/downloads', 'data.csv')
cy.readFile('cypress/downloads/data.csv')
Sample Program

This test downloads a text file from a URL and checks if it exists in the downloads folder.

Cypress
describe('File Download Verification', () => {
  it('should download and verify the file', () => {
    const url = 'https://example.com/sample.txt'
    const downloadFolder = 'cypress/downloads'
    const fileName = 'sample.txt'

    cy.downloadFile(url, downloadFolder, fileName)
    cy.readFile(`${downloadFolder}/${fileName}`)
  })
})
OutputSuccess
Important Notes

Make sure to add the cy.downloadFile custom command or use a plugin like cypress-downloadfile.

Set the download folder path correctly in your Cypress config to avoid confusion.

Always clean the downloads folder before tests to avoid false positives.

Summary

File download verification ensures users get the correct files.

Use cy.downloadFile to download and cy.readFile to check the file.

Clear downloads folder before tests to keep results accurate.