javascript 无法获取cypress详细信息中的specName,specName

wljmcqd8  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(107)

我在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文件夹之外,我不能在屏幕截图文件名中添加规范名称

30byixjq

30byixjq1#

您可以使用cy.state()获取测试标题,

cy.task('sendSpecNameToPlugin', cy.state('test').title)

但是在任务中,如果你想让路径是cypress/screenshots/testname/testname--timestamp.png,那么在after:screenshot钩子中调整你的代码,像这样

const filename = `${testname}--${timeStamp} (failed).png`;
const path = `../../screenshots/${testname}`
const newPath = `${path}/${filename}`

如果cy.state有typescript错误,请添加类型定义

cypress.d.ts

export {}

declare global {
  namespace Cypress {
    interface cy {
      state: any;          
    }
  }
}

相关问题