0
0
CypressHow-ToBeginner ยท 4 min read

How to Use after Hook in Cypress for Test Cleanup

In Cypress, use the after hook to run code once after all tests in a describe block finish. It is useful for cleanup tasks like resetting data or logging out users after tests complete.
๐Ÿ“

Syntax

The after hook in Cypress runs a function once after all tests inside a describe block have finished. It takes a callback function where you put the cleanup code.

Structure:

  • after(() => { ... }): Runs after all tests in the current suite.
javascript
describe('My Test Suite', () => {
  after(() => {
    // cleanup code here
  });

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

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

Example

This example shows using after to clear cookies after all tests run. It helps keep tests independent by cleaning up the browser state.

javascript
describe('User Login Tests', () => {
  after(() => {
    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('logs out successfully', () => {
    cy.get('#logout').click();
    cy.url().should('include', '/login');
  });
});
Output
Test suite runs two tests and then clears cookies after all tests pass.
โš ๏ธ

Common Pitfalls

Common mistakes when using after include:

  • Trying to use after inside an it block (it must be inside describe).
  • Using after for setup tasks instead of cleanup (use before or beforeEach for setup).
  • Not waiting for asynchronous commands inside after, which can cause flaky tests.
javascript
describe('Wrong Usage', () => {
  it('test with after inside it', () => {
    // This is incorrect and will cause errors
  });
});

// Correct usage:
describe('Correct Usage', () => {
  after(() => {
    // cleanup code here
  });

  it('test 1', () => {
    // test code
  });
});
๐Ÿ“Š

Quick Reference

after Hook Summary:

  • Runs once after all tests in a describe block.
  • Used for cleanup tasks like clearing cookies, resetting data, or logging out.
  • Must be declared inside describe, not inside it.
  • Supports asynchronous Cypress commands.
โœ…

Key Takeaways

Use after inside describe to run cleanup code once after all tests finish.
after is ideal for tasks like clearing cookies or resetting test data.
Do not place after inside individual tests (it blocks).
Ensure asynchronous commands inside after are properly chained to avoid flaky tests.
For setup before tests, use before or beforeEach instead.