0
0
Cypresstesting~10 mins

beforeEach and afterEach hooks in Cypress - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test suite uses beforeEach to visit the homepage before each test and afterEach to clear cookies after each test. It verifies the page title and the presence of a login button.

Test Code - Cypress
Cypress
describe('Homepage tests with hooks', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io')
  })

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

  it('checks the page title', () => {
    cy.title().should('include', 'Kitchen Sink')
  })

  it('checks the login button is visible', () => {
    cy.get('button#login').should('be.visible')
  })
})
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test suite startsNo browser opened yet-PASS
2beforeEach hook runs: cy.visit('https://example.cypress.io')Browser opens and navigates to https://example.cypress.io homepage-PASS
3Test 1 runs: cy.title().should('include', 'Kitchen Sink')Homepage loaded with title containing 'Kitchen Sink'Page title includes 'Kitchen Sink'PASS
4afterEach hook runs: cy.clearCookies()Cookies cleared from browser-PASS
5beforeEach hook runs again: cy.visit('https://example.cypress.io')Browser reloads homepage-PASS
6Test 2 runs: cy.get('button#login').should('be.visible')Homepage loaded with login button visibleLogin button with id 'login' is visiblePASS
7afterEach hook runs again: cy.clearCookies()Cookies cleared from browser-PASS
Failure Scenario
Failing Condition: The login button with id 'login' is not present or not visible on the page
Execution Trace Quiz - 3 Questions
Test your understanding
What does the beforeEach hook do in this test suite?
AChecks the page title
BVisits the homepage before each test
CClears cookies after each test
DClicks the login button
Key Result
Using beforeEach and afterEach hooks helps keep tests clean and independent by setting up and cleaning up the test environment automatically before and after each test.