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:
- Install the node module using the following command:
npm i --save-dev cypress-downloadfileAlternatively, you can specify the
npm_dependenciesinbrowserstack.jsonas shown in the following example:browserstack.json
"run_settings": { ... "npm_dependencies": { "cypress-downloadfile": "^1.2.1", }, ... }, - Update the
commands.jsfile with thedownloadFileCommanddependency in thecypress/supportdirectory using the following code:cypress/support/commands.js
require('cypress-downloadfile/lib/downloadFileCommand'); - Update the
index.jsfile with thedownloadFileplugin support in thecypress/pluginsdirectory using the following code:cypress/plugins/index.js
const {downloadFile} = require('cypress-downloadfile/lib/addPlugin'); module.exports = (on, config) => { on('task', {downloadFile}); } - Use the
cy.downloadFilecommand 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
Downloadsargument in the above sample script downloads the specified file to the./Downloadsdirectory within the BrowserStack machine running your Cypress tests. You can also specify a different download directory.