Search code examples
testingautomated-testscypress

Cypress - check test failure in global afterEach


Is there a possibility to check in global afterEach if test (it) failed?

Such global afterEach is located in support/index.js:

afterEach(() => {
  // check if test failed and perform some actions
})

Solution

  • You can use afterEach hook and remain in the scope of the Cypress context (where cy commands are available), for example:

    afterEach(function() {
        if (this.currentTest.state === 'failed') {
            // your code
        }
    });
    

    Reference: https://github.com/cypress-io/cypress/discussions/15047

    Or you can use test:after:run event and switch to node context (where any kind of node code can be executed outside of the scope of Cypress, like accessing database or file system), for example:

    Cypress.on('test:after:run', (test, runnable) => {
        if (test.state === 'failed') {
            // your code
        }
    });
    

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