Home > Software engineering >  How run test after fail in Cypress?
How run test after fail in Cypress?

Time:01-10

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.

CodePudding user response:

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

CodePudding user response:

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();
  }
});
  • Related