File download verification in Cypress - Build an Automation Script
/// <reference types="cypress" /> import path from 'path'; describe('File download verification', () => { const fileName = 'sample.pdf'; const downloadsFolder = Cypress.config('downloadsFolder'); const filePath = path.join(downloadsFolder, fileName); beforeEach(() => { // Clean up before test cy.task('deleteFile', filePath); cy.visit('/file-download'); }); it('should download the file successfully', () => { // Intercept the download request cy.intercept('GET', '/files/sample.pdf').as('fileDownload'); // Click the download button cy.get('#download-btn').click(); // Wait for the download request to complete cy.wait('@fileDownload'); // Verify the file exists and is not empty cy.readFile(filePath, 'binary', { timeout: 15000 }).should((buffer) => { expect(buffer.length).to.be.greaterThan(0); }); }); }); // In plugins/index.js or cypress.config.js (Node.js environment), add: // const fs = require('fs'); // module.exports = (on, config) => { // on('task', { // deleteFile(filePath) { // if (fs.existsSync(filePath)) { // fs.unlinkSync(filePath); // } // return null; // } // }); // }
This test script uses Cypress to automate the file download verification.
We define the file name and the downloads folder path using Cypress.config('downloadsFolder') to avoid hardcoding paths.
Before each test, we delete the file if it exists to ensure a clean state.
We visit the file download page, then intercept the GET request for the file to wait for it properly.
After clicking the download button, we wait for the download request to finish.
Finally, we read the downloaded file in binary mode and assert that its size is greater than zero, confirming the file was downloaded successfully.
The deleteFile task is a Node.js helper to remove the file before the test starts, preventing false positives.
Now add data-driven testing with 3 different file names and verify each downloads correctly