我在cypress中创建了一个函数,它会在失败时进行截图,并在截图上放置一个自定义文件名,然后将其保存在特定的库中。takess.ts
:
export function renameAndMoveScreenshot(details: any) {
let specName = ''; // Initialize specName variable
sendSpecNameToPlugin: (name:string) => specName = name;
Cypress.on('after:screenshot', () => {
const testname = (details.specName || specName).replace(/\.|\/|\s/g, '_');
const timeStamp = new Date().toISOString().replace(/:/g, '_');
const filename = `${testname}--${timeStamp} (failed).png`;
const path = '../../screenshots';
const newPath = `${path}/${filename}`;
console.log (newPath)
if (!fs.existsSync(path)) {
console.log('creating directory')
fs.mkdirSync(path, { recursive: true });
}
return new Promise((resolve, reject) => {
fs.rename(details.path, newPath, (err: any) => {
if (err) {
reject(err);
} else {
resolve({ path: newPath });
}
});
});
});`
Cypress.config.ts
setupNodeEvents(on, config) {
on('task', {
sendSpecNameToPlugin: (name) => specName = name
});
on('after:screenshot', (details) => {
return nodeEvents.renameAndMoveScreenshot(details)
})
}
login.spec.ts
:
/// <reference types="cypress"/>
describe('screenshot test', () => {
beforeEach(()=>{
cy.visit('/')
});
it('Visits the hr test', () => {
cy.task('sendSpecNameToPlugin', Cypress.spec.name)
cy.screenshot('test')
)}
})
index.ts
:
export * from './lib/takess';
我想将截图文件名保存在此目录中:
柏树属
>dist\cypress\apps\hr
>screenshtos
>login.cy.ts
我无法获得规范名称。所以我的屏幕截图保存在login.cy.ts文件夹之外,我不能在屏幕截图文件名中添加规范名称
!
1条答案
按热度按时间30byixjq1#
您可以使用
cy.state()
获取测试标题,但是在任务中,如果你想让路径是
cypress/screenshots/testname/testname--timestamp.png
,那么在after:screenshot
钩子中调整你的代码,像这样如果
cy.state
有typescript错误,请添加类型定义cypress.d.ts