Cypress Verify File Download

Profile picture for user devraj

In Cypress, you can verify whether the file is downloaded using two ways. You can use Cypress readFile command, or another technique is using the verify download plugin. readFile is the recommended way, and it supports most file formats and allows you to read the file's content. If any file format is not supported using readFile, or you want a partial file name match without custom coding, you can use the verify download plugin. Download plugin also supports interval pooling with a timeout.

Table of Content

  1. Verify Download using readFile command
  2. Verify Download using verify Downloads Plugin
  3. Video Tutorial

1. Verify Download using readFile command

By default, cy.readFile() asserts that the file exists and will fail if it does not exist. It will retry reading the file if it does not initially exist until the file exists or the command times out.

cy.readFile('cypress/downloads/sample.txt')

The above command will verify whether the sample.txt file exists or not. If the file size is large, you can increase the timeout to avoid failures.

cy.readFile('cypress/downloads/sample.txt', {timeout: 25000})

With the read file command, you can verify the file's content like in the below code or perform many other operations on the file.

cy.readFile('cypress/downloads/sample.txt').should('contain', 'my sample file')

2. Verify Download using verify downloads plugin

You can verify any file format not supported by the readFile using this plugin. It also supports partial file name match, timeout, and interval pooling. Follow the below steps to install this plugin.

Step 1: Type the below command in Terminal.

npm i -D cy-verify-downloads

Step 2: Add the below line to your project's cypress/support/e2e.js or cypress/support/commands.js

require('cy-verify-downloads').addCustomCommand();

Step 3: Add the following lines of code to your project's cypress.config.js

const { verifyDownloadTasks } = require('cy-verify-downloads');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', verifyDownloadTasks);
    },
  },
});
Verify File download
cy.verifyDownload('sample.txt');

By default, it will look for the file in the cypress/downloads folder. You do not need to mention it as we did for the readFile command.

Verify Download by Partial Name

You can specify file extension or partial file name.

cy.verifyDownload('.txt', { contains: true });
cy.verifyDownload('sam', { contains: true });
Increase Timeout

You can increase the timeout using below command.

cy.verifyDownload('sample.txt', { timeout: 15000 });

You can also increase timeout with pooling:

cy.verifyDownload('sample.txt', { timeout: 15000, interval: 600 });

Video Tutorial: Cypress Check Downloaded File