Test File Download in Cypress
Learn how to test file downloads for your Cypress test running on the BrowserStack infrastructure.
You will learn the following in this guide:
- How to download and save a file within a Cypress test
- How to access the downloaded file in your tests
Download a file in a Cypress test
In the following example, we have used the cypress-downloadfile NPM package to easily download a file from within a Cypress test.
Please follow the steps below to use the package to write a file download Cypress test:
- Install the module using the command below:
npm i --save-dev cypress-downloadfile
- Update the
npm_dependencies
inbrowserstack.json
with the following entry:
browserstack.json"run_settings": { ... "npm_dependencies": { "cypress-downloadfile": "^1.2.1", }, ... },
- Add the following line to
cypress/support/commands.js
:
cypress/support/commands.jsrequire('cypress-downloadfile/lib/downloadFileCommand')
- Add the following line to
cypress/plugins/index.js
:
cypress/plugins/index.jsmodule.exports = (on, config) => { on('task', {downloadFile}) }
- Following is a sample test case showing the usage of the file download example:
cypress/plugins/index.jscontext('downloadFile', () => { it('downlaod file in mentioned dir', () => { cy.downloadFile('https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg','Downloads','cypress-example.jpg') cy.readFile("./Downloads/cypress-example.jpg") }) })
In the sample script above, the 2nd argument is
Downloads
which means that the specified file will be downloaded in the./Downloads
directory within the BrowserStack machine where your Cypress tests are executing from. If that directory is not already available, then Cypress would create that directory and save the file in that directory. You can also specify any other path for the download directory.
Access the downloaded file in tests
As seen on the sample script on the section above, once the file has been downloaded, you can access the file using any of the applicable Cypress commands. In the above example, we have used the following command to read the file contents:
cy.readFile("./Downloads/cypress-example.jpg")
We're sorry to hear that. Please share your feedback so we can do better
Contact our Support team for immediate help while we work on improving our docs.
We're continuously improving our docs. We'd love to know what you liked
We're sorry to hear that. Please share your feedback so we can do better
Contact our Support team for immediate help while we work on improving our docs.
We're continuously improving our docs. We'd love to know what you liked
Thank you for your valuable feedback!