Bird
Raised Fist0
Cypresstesting~15 mins

File download verification in Cypress - Build an Automation Script

Choose your learning style10 modes available
Verify file download functionality
Preconditions (1)
Step 1: Click on the download button with id 'download-btn'
Step 2: Wait for the file to be downloaded
Step 3: Check the default download folder for the file named 'sample.pdf'
✅ Expected Result: The file 'sample.pdf' is downloaded successfully to the default download folder
Automation Requirements - Cypress
Assertions Needed:
Verify the file exists in the download folder
Verify the file size is greater than zero
Best Practices:
Use cy.intercept to wait for the download request
Use cy.readFile with proper path to check file existence
Avoid hardcoding absolute paths; use Cypress.config('downloadsFolder')
Clean up downloaded files before test run
Automated Solution
Cypress
/// <reference types="cypress" />

import path from 'path';

describe('File download verification', () => {
  const fileName = 'sample.pdf';
  const downloadsFolder = Cypress.config('downloadsFolder');
  const filePath = path.join(downloadsFolder, fileName);

  beforeEach(() => {
    // Clean up before test
    cy.task('deleteFile', filePath);
    cy.visit('/file-download');
  });

  it('should download the file successfully', () => {
    // Intercept the download request
    cy.intercept('GET', '/files/sample.pdf').as('fileDownload');

    // Click the download button
    cy.get('#download-btn').click();

    // Wait for the download request to complete
    cy.wait('@fileDownload');

    // Verify the file exists and is not empty
    cy.readFile(filePath, 'binary', { timeout: 15000 }).should((buffer) => {
      expect(buffer.length).to.be.greaterThan(0);
    });
  });
});

// In plugins/index.js or cypress.config.js (Node.js environment), add:
// const fs = require('fs');
// module.exports = (on, config) => {
//   on('task', {
//     deleteFile(filePath) {
//       if (fs.existsSync(filePath)) {
//         fs.unlinkSync(filePath);
//       }
//       return null;
//     }
//   });
// }

This test script uses Cypress to automate the file download verification.

We define the file name and the downloads folder path using Cypress.config('downloadsFolder') to avoid hardcoding paths.

Before each test, we delete the file if it exists to ensure a clean state.

We visit the file download page, then intercept the GET request for the file to wait for it properly.

After clicking the download button, we wait for the download request to finish.

Finally, we read the downloaded file in binary mode and assert that its size is greater than zero, confirming the file was downloaded successfully.

The deleteFile task is a Node.js helper to remove the file before the test starts, preventing false positives.

Common Mistakes - 4 Pitfalls
Not waiting for the download request to complete before checking the file
{'mistake': 'Hardcoding absolute file paths for the download folder', 'why_bad': 'This makes the test brittle and not portable across different machines or environments.', 'correct_approach': "Use Cypress.config('downloadsFolder') to get the downloads folder path dynamically."}
Not cleaning up the downloaded file before the test
{'mistake': 'Using cy.readFile without specifying encoding or mode', 'why_bad': 'Reading binary files without proper mode can cause corrupted data or wrong assertions.', 'correct_approach': "Use 'binary' encoding in cy.readFile when checking file size or content."}
Bonus Challenge

Now add data-driven testing with 3 different file names and verify each downloads correctly

Show Hint

Practice

(1/5)
1. What is the main purpose of file download verification in Cypress testing?
easy
A. To speed up the test execution time
B. To ensure the downloaded file is correct and complete
C. To check the website's loading speed
D. To verify the page layout after download

Solution

  1. Step 1: Understand file download verification

    File download verification checks if the file users get is the right one and fully downloaded.
  2. Step 2: Identify the main goal

    The goal is to confirm the file content and completeness, not speed or layout.
  3. Final Answer:

    To ensure the downloaded file is correct and complete -> Option B
  4. Quick Check:

    File correctness = B [OK]
Hint: File download verification checks file correctness, not speed [OK]
Common Mistakes:
  • Confusing download verification with page speed testing
  • Thinking it checks page layout after download
  • Assuming it speeds up tests
2. Which Cypress command is used to read the contents of a downloaded file for verification?
easy
A. cy.readFile()
B. cy.getFile()
C. cy.downloadFile()
D. cy.checkFile()

Solution

  1. Step 1: Identify commands related to file handling

    cy.downloadFile() downloads files, cy.readFile() reads file contents.
  2. Step 2: Choose the command to read file contents

    To verify file content, cy.readFile() is used, not cy.downloadFile().
  3. Final Answer:

    cy.readFile() -> Option A
  4. Quick Check:

    Read file = cy.readFile() = A [OK]
Hint: Use cy.readFile() to check file content after download [OK]
Common Mistakes:
  • Using cy.downloadFile() to read file content
  • Assuming cy.getFile() exists
  • Confusing cy.checkFile() with real commands
3. Given the code snippet:
cy.downloadFile('https://example.com/report.pdf', 'cypress/downloads', 'report.pdf')
  .then(() => {
    cy.readFile('cypress/downloads/report.pdf').should('exist')
  })

What will this test verify?
medium
A. That the downloads folder is empty before download
B. That the file 'report.pdf' is empty
C. That the URL 'https://example.com/report.pdf' is reachable
D. That the file 'report.pdf' exists in the downloads folder after download

Solution

  1. Step 1: Analyze the downloadFile command

    The command downloads 'report.pdf' to 'cypress/downloads'.
  2. Step 2: Analyze the readFile assertion

    It checks if 'report.pdf' exists in the downloads folder after download.
  3. Final Answer:

    That the file 'report.pdf' exists in the downloads folder after download -> Option D
  4. Quick Check:

    File existence check = D [OK]
Hint: Check file existence with cy.readFile().should('exist') [OK]
Common Mistakes:
  • Assuming it checks file content or emptiness
  • Thinking it tests URL reachability
  • Confusing pre-download folder state with post-download check
4. Identify the error in this Cypress test code for file download verification:
cy.downloadFile('https://example.com/data.csv', 'cypress/downloads', 'data.csv')
cy.readFile('cypress/downloads/data.csv').should('contain', 'Name, Age')
medium
A. Wrong assertion method; should use 'exist' instead of 'contain'
B. Incorrect file path in readFile command
C. Missing chaining or waiting for download to complete before reading file
D. cy.downloadFile does not exist in Cypress

Solution

  1. Step 1: Check command sequence and chaining

    The download and readFile commands run separately without waiting for download to finish.
  2. Step 2: Identify the need for chaining or waiting

    Without chaining or waiting, readFile may run before download completes, causing test failure.
  3. Final Answer:

    Missing chaining or waiting for download to complete before reading file -> Option C
  4. Quick Check:

    Wait for download before readFile = C [OK]
Hint: Chain commands or wait to ensure download finishes before reading [OK]
Common Mistakes:
  • Running readFile immediately without waiting
  • Assuming cy.downloadFile is not a valid command
  • Using wrong assertion method for content check
5. You want to verify that a downloaded CSV file contains the header 'ID, Name, Email' and is not empty. Which Cypress test code correctly achieves this?
hard
A. cy.downloadFile('https://example.com/users.csv', 'cypress/downloads', 'users.csv') .then(() => { cy.readFile('cypress/downloads/users.csv').should('contain', 'ID, Name, Email').and('not.be.empty') })
B. cy.readFile('cypress/downloads/users.csv').should('contain', 'ID, Name, Email') cy.downloadFile('https://example.com/users.csv', 'cypress/downloads', 'users.csv')
C. cy.downloadFile('https://example.com/users.csv', 'cypress/downloads', 'users.csv') cy.readFile('cypress/downloads/users.csv').should('exist')
D. cy.downloadFile('https://example.com/users.csv', 'cypress/downloads', 'users.csv') .then(() => { cy.readFile('cypress/downloads/users.csv').should('be.empty') })

Solution

  1. Step 1: Ensure download completes before reading file

    cy.downloadFile('https://example.com/users.csv', 'cypress/downloads', 'users.csv') .then(() => { cy.readFile('cypress/downloads/users.csv').should('contain', 'ID, Name, Email').and('not.be.empty') }) chains .then() after downloadFile to wait for completion.
  2. Step 2: Verify file contains header and is not empty

    cy.downloadFile('https://example.com/users.csv', 'cypress/downloads', 'users.csv') .then(() => { cy.readFile('cypress/downloads/users.csv').should('contain', 'ID, Name, Email').and('not.be.empty') }) uses should('contain', ...) and .and('not.be.empty') correctly to check content and non-empty file.
  3. Final Answer:

    cy.downloadFile('https://example.com/users.csv', 'cypress/downloads', 'users.csv') .then(() => { cy.readFile('cypress/downloads/users.csv').should('contain', 'ID, Name, Email').and('not.be.empty') }) -> Option A
  4. Quick Check:

    Chain download and readFile with content checks = A [OK]
Hint: Chain downloadFile with readFile and use should contain + not.be.empty [OK]
Common Mistakes:
  • Not chaining download and readFile causing timing issues
  • Checking file existence only without content validation
  • Asserting file is empty instead of not empty
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard