Issue handling file download from cypress

Viewed 4816

While I was working on Cypress trying to download a .xlsx report and further manipulate the data in it for further verification, problem I faced was when Cypress was running test with the electron browser-it prompted a window based popup. Moreover, when i selected chrome browser for running tests, the default directory of download directory could not be modified. Hence, manipulation of data wasn't possible if it's not present in the project directory as it would cause faliures in the CI execution... Any workaround for this would be appreciated.

2 Answers

I solved it with the index.js file in the plugins folder by doing the following stuff:

const cypressTypeScriptPreprocessor = require('./cy-ts-preprocessor');
const path = require('path');
const fs = require('fs');

const RESULT_FOLDER = 'results';
const downloadDirectory = path.join(__dirname, '..', RESULT_FOLDER);

module.exports = on => {
    on('file:preprocessor', cypressTypeScriptPreprocessor);
    on('before:browser:launch', (browser = {}, options) => {
        if (fs.existsSync(downloadDirectory)) {
            fs.rmdirSync(downloadDirectory, { recursive: true });
        }

        if (browser.family === 'chromium' && browser.name !== 'electron') {
            options.preferences.default['download'] = { default_directory: downloadDirectory };

            return options;
        }

        if (browser.family === 'firefox') {
            options.preferences['browser.download.dir'] = downloadDirectory;
            options.preferences['browser.download.folderList'] = 2;

            return options;
        }
    });
};

The documentation for that you will find here: https://docs.cypress.io/api/plugins/browser-launch-api.html#Change-download-directory

Be aware this works for Chromium browsers but currently not for the Electron browser in CI mode. Cypress knows about the issue and is currently implementing a solution for that: https://github.com/cypress-io/cypress/issues/949#issuecomment-755975882

You can change the download path in your test like below.

const downloadFolder = path.resolve(__dirname, '../users/user/source/repos/containingRoot/cypress/downloads');
Related