Search code examples
cypressuitest

How to check for file in download folder and if exist delete in cypress


I have to download a excel file lets say "someData.xlsx" during test execution meanwhile before downloading also have to put a check over download folder if "someData.xlsx" exist in download folder delete it before downloading the newly updated file. could someone explain how to achieve this ?

I tried this but getting fs.readdirSync is not a function

fs.readdirSync('./downloads').forEach((file) => {
                fs.unlinkSync(`./downloads/${file}`);
              }); 

Solution

  • install cypress-delete-downloads-folder by npm i -D cypress-delete-downloads-folder

    in plugins/index.js

    const fs = require("fs");
    const { removeDirectory } = require('cypress-delete-downloads-folder');
    
    
    module.exports = (on, config) => {
    //task to check if file exist
      on("task", {
         isFileExist( filePath ) {
          return new Promise((resolve, reject) => {
            try {
              let isExists = fs.existsSync(filePath)
              resolve(isExists);
            } catch (e) {
              reject(e);
            }
          });
        }
      });
    //to remove directory
    on('task', { removeDirectory });
    }
    

    in support/commands.js

    require('cypress-delete-downloads-folder').addCustomCommand();
    

    in your test spec file

    const path = require('path');
    
    
    describe('check for file in download folder and if exist delete', () => {
        it('delete download folder', () => {
            
            cy.task("isFileExist", { fileName: `.${path.sep}downloads${path.sep}fileName.xlsx`}).then(() => {
                cy.deleteDownloadsFolder()
            });