0
0
CypressHow-ToBeginner ยท 4 min read

How to Use afterEach in Cypress for Test Cleanup

In Cypress, use the afterEach hook to run code after every test in a test suite. This is useful for cleanup tasks like resetting data or clearing cookies to keep tests independent and reliable.
๐Ÿ“

Syntax

The afterEach hook takes a callback function that runs after each it test in the current describe block. It helps perform cleanup or reset actions.

Structure:

  • afterEach(() => { ... }): Runs after each test.
  • Place inside describe or globally in the test file.
javascript
describe('My Test Suite', () => {
  afterEach(() => {
    // Code here runs after each test
  });

  it('Test 1', () => {
    // test code
  });

  it('Test 2', () => {
    // test code
  });
});
๐Ÿ’ป

Example

This example shows using afterEach to clear cookies after every test, ensuring no leftover cookies affect other tests.

javascript
describe('User Login Tests', () => {
  afterEach(() => {
    cy.clearCookies();
  });

  it('logs in successfully', () => {
    cy.visit('/login');
    cy.get('#username').type('user1');
    cy.get('#password').type('password');
    cy.get('button[type=submit]').click();
    cy.url().should('include', '/dashboard');
  });

  it('fails login with wrong password', () => {
    cy.visit('/login');
    cy.get('#username').type('user1');
    cy.get('#password').type('wrongpass');
    cy.get('button[type=submit]').click();
    cy.get('.error').should('be.visible');
  });
});
Output
Test 1: passes Test 2: passes Cookies cleared after each test
โš ๏ธ

Common Pitfalls

Common mistakes when using afterEach include:

  • Placing afterEach outside describe unintentionally, causing unexpected global effects.
  • Not cleaning up asynchronous actions properly, leading to flaky tests.
  • Using afterEach for setup tasks instead of cleanup.

Always ensure cleanup code is synchronous or returns a Cypress command to handle async properly.

javascript
describe('Wrong Usage', () => {
  afterEach(() => {
    // Wrong: async code without returning Cypress command
    setTimeout(() => {
      cy.log('This may not run as expected');
    }, 1000);
  });

  it('test example', () => {
    cy.visit('/');
  });
});

// Correct way:
describe('Correct Usage', () => {
  afterEach(() => {
    // Return Cypress command to ensure proper execution
    return cy.clearCookies();
  });

  it('test example', () => {
    cy.visit('/');
  });
});
๐Ÿ“Š

Quick Reference

FeatureDescriptionExample
afterEachRuns after each test in a describe blockafterEach(() => { cy.clearCookies(); })
PlacementInside describe or globally in test filedescribe('suite', () => { afterEach(...) })
Use caseCleanup tasks like clearing cookies or resetting stateafterEach(() => { cy.resetDb(); })
Async handlingReturn Cypress commands or use synchronous codeafterEach(() => cy.clearLocalStorage())
โœ…

Key Takeaways

Use afterEach to run cleanup code after every test to keep tests independent.
Place afterEach inside describe blocks to scope cleanup to that suite.
Always return Cypress commands or use synchronous code in afterEach for reliability.
Avoid using afterEach for setup tasks; it is meant for cleanup after tests.
Common cleanup tasks include clearing cookies, local storage, or resetting test data.