0
0
Cypresstesting~5 mins

beforeEach and afterEach hooks in Cypress

Choose your learning style9 modes available
Introduction

We use beforeEach and afterEach hooks to run some code before or after every test. This helps keep tests clean and avoid repeating the same steps.

When you want to open a webpage before each test runs.
When you need to reset data or clear cookies after each test.
When you want to log in once before every test in a group.
When you want to clean up test data after each test finishes.
Syntax
Cypress
beforeEach(() => {
  // code to run before each test
});

afterEach(() => {
  // code to run after each test
});

Hooks run automatically before or after every it test inside the same describe block.

You can have multiple hooks in one test file.

Examples
This opens the website before every test.
Cypress
beforeEach(() => {
  cy.visit('https://example.com')
});
This clears cookies after every test to keep tests independent.
Cypress
afterEach(() => {
  cy.clearCookies()
});
This logs in before each test inside the describe block.
Cypress
describe('My tests', () => {
  beforeEach(() => {
    cy.login('user', 'pass')
  });

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

  it('Test 2', () => {
    // test code
  });
});
Sample Program

This test suite visits the page before each test and clears cookies after each test. It checks the page title and a visible link.

Cypress
describe('Simple tests with hooks', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io')
  });

  afterEach(() => {
    cy.clearCookies()
  });

  it('Has correct title', () => {
    cy.title().should('include', 'Kitchen Sink')
  });

  it('Contains commands link', () => {
    cy.contains('Commands').should('be.visible')
  });
});
OutputSuccess
Important Notes

Hooks help avoid repeating setup or cleanup code in every test.

Use before and after hooks if you want code to run once before or after all tests.

Keep hooks simple and fast to avoid slowing down tests.

Summary

beforeEach runs code before every test.

afterEach runs code after every test.

They help keep tests clean and avoid repeating code.