1

In my mochawesome-report addContext() is keeping previous count and adding it to each 'it' scenario, in case of a test case failure, I'm adding 'someValue' as context to the test case. So if 2nd test case fails then value is getting printed twice.

Following is the snapshot:

enter image description here

Following is my afterEach() method :

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'
        })
      });
    } 
  })
Kushal Bhalaik
  • 3,349
  • 5
  • 23
  • 46

3 Answers3

1

Got what I was looking from https://docs.cypress.io/api/events/catalog-of-events.html#Cypress-Events

enter image description here

Though I'll have to remove Cypress.on('test:after:run', afterEach()

So I'll have to specify Cypress.on('test:after:run', in each spec file

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

which is kind of put off, it would be better to put this whole code in support/command.js

Kushal Bhalaik
  • 3,349
  • 5
  • 23
  • 46
1

You can add this code :

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

inside "support/index.js" and you will have the screenshot of the failed test within your reports

Anas Einea
  • 61
  • 1
  • 3
0

Workaround if you need to use it within tests (using test id)

In your 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)
    })
})

And now you can use it within your test (getting the test.id)

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