In this article, we will discuss how we can download a file in cypress using the cypress-downloadfile node package. Let’s automate the below Test scenario:

1.Download a file from https://www.learningcontainer.com/wp-content/uploads/2020/04/sample-text-file.txt to our desired location.
2. Validate the contents of the file.

Step 1: Install the cypress-downloadfile node package using the command:

1
npm install --save -dev cypress-downloadfile

Once you have installed the package successfully, you can see the package name in your package.json file

cypress package json with download file node package
 

Step 2: Add the following line to cypress/support/commands.js

1
require('cypress-downloadfile/lib/downloadFileCommand')

cypress download in command js

Add the following lines to cypress/plugins/index.js

1
2
3
4
const {downloadFile} = require('cypress-downloadfile/lib/addPlugin')
module.exports = (on, config) => {
  on('task', {downloadFile})
}

cypress download plugin/index js
 

Step 3:

1
2
3
4
5
6
7
8
describe('Example to demonstrate file download in cypress', function () {

    it('File Download using cypress-downloadfile npm package', () => {
        cy.downloadFile('https://www.learningcontainer.com/wp-content/uploads/2020/04/sample-text-file.txt',
            'cypress/fixtures/Download', 'test.txt')
        cy.readFile('cypress/fixtures/Download/test.txt').should('contain', 'Lorem ipsum dolor sit amet')    
    })
})

cypress code for file download

cy.downloadFile(‘https://www.learningcontainer.com/wp-content/uploads/2020/04/sample-text-file.txt’, ‘cypress/fixtures/Download’, ‘test.txt’) will download the file from the download link to cypress/fixtures/Download folder. Cypress will automatically create Download folder under fixtures, if it is not there previously. cy.readFile(‘cypress/fixtures/Download/test.txt’).should(‘contain’, ‘Lorem ipsum dolor sit amet’) will check that the downloaded text file contains the text Lorem ipsum dolor sit amet.
 

Step 4: After Successful execution:

cypress download file test execution

Do check out πŸ™‚

Github:Β https://github.com/alapanme/Cypress-Automation
All Cypress Articles: https://testersdock.com/cypress-tutorial/