NodeJS 多次执行Cypress并将结果保存在不同屏幕截图中的问题Cypress版本12.10.0中的文件夹

rlcwz9us  于 2023-05-22  发布在  Node.js
关注(0)|答案(3)|浏览(102)

我试图创建一个文件夹来保存我从Cypress捕获的屏幕截图,在屏幕截图内的自定义文件夹中,在screenshotFolder文件夹中,每次执行run.cypress()时都会动态添加一个包含日期的文件夹,但它不起作用。
问题是,当执行run.cypress()代码时,它在最后更改了我放置的路由,并保留了默认的路由。
可以执行的代码如下:

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);
});

在第一次执行的输出是,这表明我不工作:

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

因此,发生了什么,这是什么出现在下面的图像:

每次执行都应该包含捕获的文件存储在您创建的文件夹之外,并且也会覆盖testWeb.cy.js文件夹(每个执行文件夹都应该有一个这样命名的文件夹)。
此外,我们可以看到,与报告,它的工作相当不错。
我该怎么解决?

cyej8jka

cyej8jka1#

Wandille是正确的,你只是把配置设置在了错误的地方-所以我怀疑你是在挣扎的基本知识。
我建议使用before()来设置截图路径,这样的变化不仅适用于模块API调用,还适用于cypress runcypress 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)
  })
})

注意事项:

  • 所需额外路径myScreenshotsFolder将自动添加到基本路径cypress/screenshots
  • 如果你的测试定义了一个文件名cy.screenshot('some-file-name'),它将被使用,否则将使用测试标题。这遵循Cypress当前的惯例。
  • before()应该放在cypress/support/e2e.js文件中以供全局使用
niknxzdl

niknxzdl2#

screenshotsFolder应该在config部分

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
    }
});

代码源

jum4pzuy

jum4pzuy3#

需要使用Cypress APIstart函数,也可以使用path.join方法定义文件夹路径。
我刚刚更新了你现有的代码,你可以试试这个:-

const path = require('path');

folderName = 'ROX';

var datetime = new Date();
datetime = datetime.toISOString().slice(0, 19).replace('T', '_');
datetime = datetime.replace(/:\s*/g, '_');

screenshotsFolder = path.join(__dirname, 'cypress', 'screenshots', folderName, datetime);

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

const cypress = require('cypress');
const { start } = require('cypress/lib/tasks/plugins');

start({
  onBeforeRun: async (options) => {
    options.config.screenshotsFolder = screenshotsFolder;
  },
}).then(async () => {
  const results = await cypress.run({

    browser: 'chrome',
    configFile: __dirname + '/cypress.config.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
        }
    },
    videosFolder: __dirname + '/cypress/videos',
  });
  
  
});

相关问题