Home > Blockchain >  Cypress - check test failure in global afterEach
Cypress - check test failure in global afterEach

Time:04-27

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

CodePudding user response:

What you seek is the after:spec and is exposed via plug-ins. You'll have access to the spec and the results. https://docs.cypress.io/api/plugins/after-spec-api#Syntax

CodePudding user response:

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

  • Related