赛普拉斯 - addContext() 保留以前的失败计数并将其添加到 mochawesome 报告中的每个 'it' 场景

Cypress - addContext() is keeping previous failure count and adding it to each 'it' scenario in mochawesome report

在我的 mochawesome-report addContext() 中保留了之前的计数并将其添加到每个 'it' 场景中,以防测试用例失败,我将添加 'someValue' 作为上下文到测试用例。因此,如果第二个测试用例失败,那么值将被打印两次。

截图如下:

以下是我的afterEach()方法:

afterEach(function () {
    if (this.currentTest.state === 'failed') {    
      var test = this.currentTest

      Cypress.on('test:after:run', (test) => {

        addContext({ test }, {
          title: 'Failing Screenshot: ' + '>> screenshots/' + Cypress.spec.name + '/' + test_name + ' -- ' + test.title + ' (failed)' + '.png <<',
          value: 'screenshots/' + Cypress.spec.name + '/' + test_name + ' -- ' + test.title + ' (failed)' + '.png'
          //value: 'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAABkCAYAAAAVORraAAACH0lEQVR'
        })
      });
    } 
  })

https://docs.cypress.io/api/events/catalog-of-events.html#Cypress-Events

得到了我想要的东西

尽管我必须删除 Cypress.on('test:after:run', afterEach()

所以我必须在每个规格文件中指定 Cypress.on('test:after:run',

const spec_name = this.title

  Cypress.on('test:after:run', (test) => {

    if (test.state === 'failed') {
      addContext({ test }, {
        title: 'Failing Screenshot: ' + '>> screenshots/' + Cypress.spec.name + '/' + spec_name + ' -- ' + test.title + ' (failed)' + '.png <<',
        value: 'screenshots/' + Cypress.spec.name + '/' + spec_name + ' -- ' + test.title + ' (failed)' + '.png'
      })
    }
  });

有点拖延,最好把整个代码放在support/command.js

您可以添加此代码:

const addContext = require('mochawesome/addContext');

Cypress.on('test:after:run', (test, runnable) => {
  if (test.state === 'failed') {
    addContext({test}, { title: "Screenshot", value:`../cypress/screenshots/${Cypress.spec.name}/${runnable.parent.title} -- ${test.title} (failed).png` })
  }
})

在 "support/index.js" 中,您将在报告中看到失败测试的屏幕截图

解决方法,如果你需要在测试中使用它(使用测试 id)

在你的support/index.js

Cypress.on('test:before:run', (test, runnable) => {
  if (!window['extra']) {
    window['extra'] = []
  }

  if (!window['extra'][test.id]) {
    window['extra'][test.id] = []
  }
})

Cypress.on('test:after:run', (test, runnable) => {
    window['extra'][test.id].map((item) => {
      addContext({ test }, item)
    })
})

现在您可以在测试中使用它(获得 test.id)

it('some test', function() {
  // Using window to bypass issue with context
        window['extra'][this.test.id].push( {
          title: 'Hello',
          value: 'World
        })  
})