重命名柏树屏幕快照

时间:2020-03-16 09:14:51

标签: javascript cypress

我正在尝试重命名为失败的赛普拉斯测试创建的屏幕截图。 我遵循了文档https://docs.cypress.io/api/plugins/after-screenshot-api.html#Modify-screenshot-details

的示例

对于测试,我正在使用赛普拉斯提供的测试套件。

只要我使用静态字符串,重命名文件就可以工作,但是当我尝试从诸如时间戳或旧路径的详细信息对象访问数据时,重命名失败。

 Error: ENOENT: no such file or directory, rename 'C:\projects\playground\cypress\screenshots\examples\actions.spec
.js\Actions-- .type() - type into a DOM element (failed).png'
-> 'C:\projects\playground\cypress\mochareports\screenshots\2020-03-16T08.55:09.929Z.png'

我的代码如下

const fs = require('fs')

//Screenshots names can be too long for the file system, taht why we truncate them
module.exports = (on, config) => {
    on('after:screenshot', (details) => {
        console.log(details) // print all details to terminal
        //const fileName = details.takenAt.replace(":",".") +".png"; // This fails

        const fileName = details.specName +".1png"; // This fails
        console.log(fileName);
        //const fileName = "test.png"; // This works
        const newPath = "cypress/mochareports/screenshots/"+ fileName;
        console.log(newPath);

        return new Promise((resolve, reject) => {
            // fs.rename moves the file to the existing directory 'new/path/to'
            // and renames the image to 'screenshot.png'
            fs.rename(details.path, newPath, (err) => {
                if (err) return reject(err)

                // because we renamed and moved the image, resolve with the new path
                // so it is accurate in the test results
                resolve({ path: newPath })
            })
        })
    })
}

让我感到困惑的是,在执行日志中,我的console.logs在实际测试的日志之前可见:

...
  Running:  examples\actions.spec.js                                                       (1 of 19)


  Actions
{
  size: 148523,
  takenAt: '2020-03-16T08:55:09.929Z',
  dimensions: { width: 1280, height: 720 },
  multipart: false,
  specName: 'examples\\actions.spec.js',
  testFailure: true,
  path: 'C:\\Projekte\\playground\\cypress\\screenshots\\examples\\actions.spec.js\\Actions -- .type() - type into a DOM element (failed).png',
  scaled: true,
  blackout: [],
  duration: 342
}
2020-03-16T08.55:09.929Z.png
cypress/mochareports/screenshots/2020-03-16T08.55:09.929Z.png
    1) .type() - type into a DOM element
    √ .focus() - focus on a DOM element (326ms)
...

在我将功能添加到after:screenshot事件之后,控制台日志是否应该在测试执行后发生?

1 个答案:

答案 0 :(得分:0)

问题是javascript代码。

const fileName = details.takenAt.replace(":",".") +".png"

失败,因为仅替换了第一个冒号而剩下了其余的。由于文件名中不允许使用冒号,因此重命名失败。

const fileName = details.takenAt.replace("/:/g",".") +".png"

这实际上取代了所有冒号,并且效果很好。

此外,将规范名称设置为文件名失败,因为规范名称将具有“ example / action.spec.js”架构。失败是因为cypress / mochareports / screenshots /中不存在目录示例。要解决此问题,有必要创建目录或将所需的文件名更改为不带斜杠的字符串。