Home  >  Q&A  >  body text

Executing cypress multiple times and saving the results in different screenshot folders in Cypress version 12.10.0: Fix issue

I'm trying to create a folder to save the screenshots captured from Cypress in a custom folder within the screenshots, where in the ScreenshotFolder folder one will be dynamically added for each execution of run.cypress() folder with dates but it doesn't work.

The problem is that when the code run.cypress() is executed, at the end it changes the route I put and keeps the default route.

The code can be executed as follows:

const cypress = require('cypress');
const fs = require('fs');
const path = require('node:path'); 

//Function that create the test run
var createRunTest = async function (info, folderNameResults){

   //Datetime will be modified every time that the function is called
   var datetime2 = new Date(); //test start date
   datetime2 = datetime2.toISOString().slice(0, 19).replace('T', '_');
   datetime2 = datetime2.replace(/:\s*/g, '_');

   //Then I create the folders of the results for reports and screenshots with the number of execution and his datetime
   //Creation datetime folder in reports (time it runs)
   var reportsFolder = path.join(__dirname, 'cypress', 'reports', folderNameResults, cronInfo.execution_num + '_' + datetime2);
   fs.mkdir(reportsFolder, (err) => {
       if (err) {
          if (err.code == 'EEXIST') return console.error("file exist");
          return console.error(err);
       }
   });

   //Creation datetime folder in screenshots (time it runs)
   var screenshotsFolder = path.join(__dirname, 'cypress', 'screenshots', folderNameResults, info.execution_num + '_' + datetime2);
   fs.mkdir(screenshotsFolder, (err) => { 
       if (err) {
          if (err.code == 'EEXIST') return console.error("file exist");
          return console.error(err);
       }
   });


   console.log("It should be: ", screenshotsFolder);

   let results = await cypress.run({
       browser: 'chrome',
       configFile: __dirname + '/cypress.config.js',
       spec: __dirname + '/cypress/e2e/investigation/testWeb.cy.js', //put your test here
       reporter: "cypress-multi-reporters",
       reporterOptions: {
           "reporterEnabled": "mochawesome",
           "mochawesomeReporterOptions": {
               "reportDir": reportsFolder + "/json/",
               "overwrite": false,
               "html": false,
               "json": true
           }
       },
       videosFolder: __dirname + '/cypress/videos',
       screenshotsFolder: screenshotsFolder,
   });
   console.log("But it is this", results.config.screenshotsFolder);

   info.execution_num += 1;

   return;
}



//Here i have information of execution times
var info = {
    id: 1
    created: new Date().toISOString().slice(0, 10),
    execution_num: 0, //execution number
}

var folderNameResults = info.id + '_' + info.created;


//here i create a folder with folderNameResults in directories "cypress/reports/ and cypress/screenshots"
//i.e. remaining as follow: cypress/reports/1_05_17_2023 (and the same with screenshots)

fs.mkdir(__dirname + '/cypress/reports/' + folderNameResults, (err) => { //creation in REPORTS
    if (err) {
        if (err.code == 'EEXIST') return console.error("file exist");
        return console.error(err);
    }
});

fs.mkdir(__dirname + '/cypress/screenshots/' + folderNameResults, (err) => { //creation in SCREENSHOTS
    if (err) {
        if (err.code == 'EEXIST') return console.error("file exist");
        return console.error(err);
    }
});


//Then i call the function to create a execution test
console.log("FIRST EXECUTION"); //increment +1 execution number (1)
createRunTest(info, folderNameResults).then( () => {
    console.log("SECOND EXECUTION");
    //increment +1 execution number (2)
    createRunTest(info, folderNameResults);
});

On the first execution, the output shows that it doesn't work:

It should be:  C:\Users\xeom\Desktop\Ayudantia\v2_script\script/cypress/screenshots/1_2023-05-17/0_2023-05-17_19_32_30

But it is this C:\Users\xeom\Desktop\Ayudantia\v2_script\script\cypress\screenshots

So what happens is as shown below:

The file containing the capture for each execution is stored outside the folder you create and is also overwritten in the testWeb.cy.js folder (each execution folder should have a folder named like this) . < /p>

Furthermore, we can see, through the report, that it works very well.

How to fix it?

P粉201448898P粉201448898204 days ago337

reply all(2)I'll reply

  • P粉356128676

    P粉3561286762024-03-30 13:47:10

    Wandille is correct, you're just setting the config in the wrong place - so I suspect you're trying to learn the basics.

    I recommend using before() to set the screenshot path so that the change applies not only to module API calls, but also to cypress run and cypress open.

    before(() => {
      const folderName = 'ROX';
      const timestamp = (new Date())
        .toISOString()
        .slice(0, 19)
        .replace('T', '_')
        .replace(/:\s*/g, '_')
      
      const myScreenshotsFolder = `${folderName}/${timestamp}`
      
      Cypress.Commands.overwrite('screenshot', (originalFn, subject, ...args) => {
        let {name, userOptions} = args
        name = `${myScreenshotsFolder}/${(name || Cypress.currentTest.title)}`
        originalFn(subject, name, userOptions)
      })
    })
    

    Comments:

    • The additional paths you want myScreenshotsFolder will be automatically added to the base path cypress/screenshots

    • Your test definition file name cy.screenshot('some-file-name') will be used, otherwise the test title will be used. This follows current Cypress practice.

    • before() should be placed in the cypress/support/e2e.js file for global use

    reply
    0
  • P粉828463673

    P粉8284636732024-03-30 09:35:11

    screenshotsFolder should be in the config section

    let results = await cypress.run({
        browser: 'chrome',
        configFile: __dirname + '/cypress.config.js',
        //spec: __dirname + '/cypress/e2e/investigacion/testWeb.cy.js',
        reporter: "cypress-multi-reporters",
        reporterOptions: {
            "reporterEnabled": "mochawesome",
            "mochawesomeReporterOptions": {
                "reportDir": "cypress/reports/" + folderName + '/' + datetime + "/json/",
                //"reportDir": "cypress/reports/json/",
                "overwrite": false,
                "html": false,
                "json": true
            }
        },
        config:{
           videosFolder: __dirname + '/cypress/videos',
           screenshotsFolder: screenshotsFolder
        }
    });

    CodeSource

    reply
    0
  • Cancelreply