1

Example:

  1. I ran the tests in cypress.
  2. Test accounts have been created
  3. Next I get a failure in one of the tests
  4. Test accounts remain created on the server
  5. After failure, I want to delete the accounts I created. For it, I have the last deleteCreatedUsers() test, but I don't know how to run it after it fails. Since the tests are interrupted after the first failed test to save time.

I need a solution to run one test after something like after fails

I did try after, afterEach and default condition if(). After fail after, afterEach don't do anything.

Yevhen
  • 11
  • 2

3 Answers3

3

There is another place to put your code if you find afterEach() does not run when the test fails.

Cypress.on('fail', (error, runner) => {
  deleteCreatedUsers();
})

The recommended approach from Cypress is to perform cleanup in beforeEach() as already mentioned, but the above event listener may also work depending on what you are doing inside deleteCreatedUsers().

2

Also try the After Run API. It runs in the Node process of Cypress, set up in cypress.config.js.

It should always run after test run, pass of fail. But your deleteCreatedUsers() sounds maybe like browser-code, you will need to adapt it for the Node process.

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  // setupNodeEvents can be defined in either
  // the e2e or component configuration
  e2e: {
    setupNodeEvents(on, config) {
      on('after:run', (results) => {
        deleteCreatedUsers()
      })
    }
  }
})

It is also possible to run in beforeEach() instead of afterEach(), that way the tests are always starting with a clear users situation.

beforeEach(() => {
  deleteCreatedUsers()
})
K.Morassi
  • 23
  • 5
0

You can create an afterEach block that contains the code here, and use the status of the test to determine whether or not to execute your code.

afterEach(() => {
  if (Cypress.mocha.getRunner().suite.ctx.currentTest.state === 'failed') {
    deleteCreatedUsers();
  }
});
agoff
  • 5,818
  • 1
  • 7
  • 20