Search code examples
downloadcypress

How do i delete downloaded file in using cypress


I'm trying to delete a downloaded file before my next text execution but not able to find a way how can I delete the downloaded file


Solution

  • The configuration option "trashAssetsBeforeRuns": true is by default true, so unless you have already changed it, that's not the answer you're looking for.

    Please be aware that it only applies to cypress run (headless) mode, ref cypress.d.ts (confirmed with a simple test).

    Also be aware of the downloadsFolder configuration option which defaults to /cypress/downloads. Outside the project, use the full path.


    For cypress open the recipe local-download-spec.js gives you an example.

    Test

    import { deleteDownloadsFolder } from './utils'
    ...
    beforeEach(deleteDownloadsFolder)
    ...
    

    Utils

    export const deleteDownloadsFolder = () => {
      const downloadsFolder = Cypress.config('downloadsFolder')
      cy.task('deleteFolder', downloadsFolder)
    }
    

    Task in /cypress/plugins/index.js

    const { rmdir } = require('fs')
    
    module.exports = (on, config) => {
      on('task', {
        deleteFolder(folderName) {
          console.log('deleting folder %s', folderName)
    
          return new Promise((resolve, reject) => {
            rmdir(folderName, { maxRetries: 10, recursive: true }, (err) => {
              if (err) {
                console.error(err)
                return reject(err)
              }
              resolve(null)
            })
          })
        },
      })
    }