0
0
Cypresstesting~5 mins

before and after hooks in Cypress

Choose your learning style9 modes available
Introduction

Before and after hooks help run setup and cleanup steps automatically in tests. They make tests easier and cleaner by avoiding repeated code.

You want to open a website before each test starts.
You need to reset data after a test finishes.
You want to log in once before running several tests.
You want to clear cookies or local storage after tests.
You want to prepare test data before running tests.
Syntax
Cypress
before(() => {
  // code to run once before all tests
});

after(() => {
  // code to run once after all tests
});

beforeEach(() => {
  // code to run before each test
});

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

before and after run once per test suite.

beforeEach and afterEach run before or after every single test.

Examples
This opens the website once before all tests run.
Cypress
before(() => {
  cy.visit('https://example.com')
});
This clears cookies once after all tests finish.
Cypress
after(() => {
  cy.clearCookies()
});
This logs in before each test to start fresh.
Cypress
beforeEach(() => {
  cy.login('user', 'pass')
});
This logs out after each test to clean up.
Cypress
afterEach(() => {
  cy.logout()
});
Sample Program

This test suite shows how hooks run in order. Logs help see when each hook and test runs.

Cypress
describe('My Test Suite', () => {
  before(() => {
    cy.log('Runs once before all tests')
  })

  after(() => {
    cy.log('Runs once after all tests')
  })

  beforeEach(() => {
    cy.log('Runs before each test')
  })

  afterEach(() => {
    cy.log('Runs after each test')
  })

  it('Test 1', () => {
    cy.log('Executing Test 1')
  })

  it('Test 2', () => {
    cy.log('Executing Test 2')
  })
})
OutputSuccess
Important Notes

Hooks help keep tests DRY (Don't Repeat Yourself).

Use beforeEach and afterEach for setup/cleanup needed for every test.

Use before and after for one-time setup or cleanup.

Summary

Before and after hooks run code automatically around tests.

Use before/after once per suite, beforeEach/afterEach per test.

They make tests cleaner and easier to maintain.