question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Downloads folder not emptying

See original GitHub issue

Current behavior

When my app downloads files, the downloads folder never gets cleared. The documentation says it should get cleared after each test, but this is not happening. I am having to use rimraf to make that happen but would love if Cypress could handle this.

On a side note, it would be really nice if their was a simple way to view the files in that downloads folder to ensure the correct file with filename downloaded as expected. Right now I have to create a task and use globby (which doesn’t seem very reliable) to make that happen.

Desired behavior

My downloads folder should get emptied after each test.

Test code to reproduce

it('can download JPG when clicking on Download digital passes button', () => {
      cy.intercept({ method: 'POST', path: '/file/location/here' }).as('interceptName');

      cy.getByAriaLabel('Download digital passes').click();

      cy.wait('@interceptName').its('request').then(({ body }) => {
        expect(body).to.have.property('someProperty', 'JPG');
      });
    });

    it('has 1 filename that contains code, Passenger Number and airport from/to codes in downloaded file', () => {
      cy.task('findFileList', `${downloadsFolder}/*.jpg`).then((fileList) => {
        const { recordLocator, segments, passengers } = window.bookingData;
        const from = segments[0].departure.airport.airportCode;
        const to = segments[segments.length - 1].arrival.airport.airportCode;
        const expectedFileName = `${downloadsFolder}/0-${passengers[0].number} ${from}-${to} (${recordLocator}).jpg`;

        expect(fileList.includes(expectedFileName)).to.equal(true);
      });
    });

// the task in plugins/index.js
  on('task', {
    // a task to find one file matching the given mask
    // returns just the first matching file
    findFileList(mask) {
      if (!mask) {
        throw new Error('Missing a file mask to seach');
      }

      console.log('searching for files %s', mask);

      return globby(mask).then((list) => {
        if (!list.length) {
          throw new Error(`Could not find files matching mask "${mask}"`);
        }

        console.log('found files: %s', list);

        return list;
      });
    },
  });

Versions

Cypress 6.4.0, latest version of OSX on Macbook Pro using Chrome 88.

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:6
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
AustinBernerEvercastcommented, Jan 6, 2022

@sousajunior @Jakejamesreid - I wrote a solution, a little hacky but it works like a charm for me for this functionality. It will clear downloads folder on cy:open

Function for clearing the downloads folder:

const system = require(‘fs’); const path = require(‘path’); const directory = ‘cypress/downloads/’;

// Delete downloaded files in cypress/downloads system.readdir(directory, (err, items) => { if (err) throw err; for (const item of items) { if(item.includes(“.”)){ system.unlink(path.join(directory, item), err => { console.log(“Removed “+item+”.”); if (err) throw err; }); } else { system.rmdir(path.join(directory,item), { recursive: true }, err => { console.log(“Removed “+item+”.”); if(err) throw err; }); } } });

Command to run, chained with cy:open, to invoke the function to clear the downloads folder node cypress/support/clearDownloads.js && cypress open

0reactions
AustinBernerEvercastcommented, Jan 7, 2022

@sousajunior Figured I would provide an update for the above solution, I’ve worked it into a beforeEach hook by utilizing the plugins file. This will clear the contents of the cypress/downloads folder before each scenario is run

Please bear in mind that there should be better error reporting here - I consider this to be minimum-viable.

The trick is to use cy.task() to get Cypress to do what you want it to, and to use it within a hook.

Here is the beforeEach hook I have set up:

beforeEach(() => {
  // runs before each test in the block
  
  // ===== VARIABLES =====
    const downloadsDirectory = "cypress/downloads/";

  // ===== FUNCTIONS =====

function clearState(){
  // function to clear user state before proceeding to next scenario
  cy.clearCookies().then(()=>{
    cy.log("Cookies were cleared.");
  })

  // Deletes downloaded files from /cypress/downloads
  cy.task('readdir',{ dirPath: downloadsDirectory}).then(arr=>{
      if(arr.length>0){
        cy.log("Found "+arr.length+" file(s) in "+downloadsDirectory+":"+"\n"+arr)
        cy.task('deleteDownloads',{ dirPath:downloadsDirectory })
        cy.task('readdir',{ dirPath: downloadsDirectory}).then(newArr=>{
          if(newArr.length==0){
            cy.log("Cleared contents of "+downloadsDirectory)
          } else {
            throw new Error("Did not clear all files from "+downloadsDirectory)
          }
        })
      } else {
        cy.log("No files were found to delete in "+downloadsDirectory)
      }
  })

// Uses baseURL set in cypress.json
cy.visit('/',{'retryOnStatusCodeFailure':true}, {timeout:10000})
}

  // ===== EXECUTION =====
  clearState();

})

Here is the content of the plugin:

//*node filesystem
const fs = require('fs');
const path = require('path');

export default (on, config) => {
on('task', {
// ===== task to use node 'fs' (filesystem) to read directory=====
  readdir({ dirPath }) {
    return new Promise((resolve,reject)=>{
      try {
        const dirData = fs.readdirSync(dirPath);
        resolve(dirData);
      } catch (e) {
        reject(e);
      }
    })
  },
  // ===== task to use node 'fs' (filesystem) to delete downloaded files from cypress/downloads
  deleteDownloads( { dirPath }) {
    fs.readdir(dirPath, (err, files) => {
        for (const file of files) {
            fs.unlink(path.join(dirPath, file), err => {
                console.log("Removed "+file);
            });
        }
    });
    return null;
  }
}
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

My Downloads folder is suddenly empty. What could have ...
Honestly I would advise against using the Downloads folder other than for downloading files, and once they are downloaded, copy them into ...
Read more >
Simple Methods To Fix Downloads Folder Not Responding On ...
Go back to your Downloads folder and check whether the document is in the folder, if it is empty go back to the...
Read more >
My Files Disappeared from Downloads. How Do I ... - Ask Leo!
Downloads is for downloads, not for storage ... An empty Downloads folder. In my opinion, the Downloads folder should never be used for...
Read more >
How to Clear Your Downloads Folder - Computer Hope
To permanently delete the files, right-click the Recycle Bin icon on your desktop and select Empty Recycle Bin in the drop-down menu that ......
Read more >
Folder Shows Empty but Files Are There Windows 10/8/7
The virus hides the files and makes the folder shows empty but has size. Other probable reasons are improper removal of the external...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found