Test File Download in Cypress

Test File Download in Cypress

Learn how to test file downloads for your Cypress test running on BrowserStack.

Overview

In Cypress, you can download a file from a web app using the cypress-downloadfile NPM package. The downloaded file is available in the ./Downloads directory within the BrowserStack machine running your Cypress tests. If such a directory does not exist, Cypress creates it and saves the file in that directory.

Depending on the type of file that you download, you can verify this file using:

  • cy.readFile: For files such as .doc, .csv, .pdf, etc.
  • cy.verifyDownload: For for files such as .zip, .png, .jpg, etc.

In this guide, you will learn how to:

Download the file in Cypress

Use the following steps to download a file from within your Cypress test:

  1. Install the node module using the following command:
    npm i --save-dev cypress-downloadfile
    

    Alternatively, you can specify the npm_dependencies in browserstack.json as shown in the following example:

    browserstack.json

    "run_settings": {
         ...
         "npm_dependencies": {
             "cypress-downloadfile": "^1.2.1",
         },
         ...
     },
    
  2. Update the commands.js file with the downloadFileCommand dependency in the cypress/support directory using the following code:

    cypress/support/commands.js

    require('cypress-downloadfile/lib/downloadFileCommand');
    
  3. Update the index.js file with the downloadFile plugin support in the cypress/plugins directory using the following code:

    cypress/plugins/index.js

    const {downloadFile} = require('cypress-downloadfile/lib/addPlugin');
    module.exports = (on, config) => {
       on('task', {downloadFile});
    }  
    
  4. Use the cy.downloadFile command in your test script to download a file from a specific URL as shown in the following code:
    context('downloadFile', () => {
     it('download file in mentioned dir', () => {
       cy.downloadFile('','Downloads','cypress-example.doc')
     })
    })
    

    The Downloads argument in the above sample script downloads the specified file to the ./Downloads directory within the BrowserStack machine running your Cypress tests. You can also specify a different download directory.

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.