Search code examples
testingcypresse2e

How run test after fail in Cypress?


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.


Solution

  • 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().