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.
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.
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') }) })
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test suite starts | No browser opened yet | — | PASS |
| 2 | beforeEach hook runs: cy.visit('https://example.cypress.io') | Browser opens and navigates to https://example.cypress.io homepage | — | PASS |
| 3 | Test 1 runs: cy.title().should('include', 'Kitchen Sink') | Homepage loaded with title containing 'Kitchen Sink' | Page title includes 'Kitchen Sink' | PASS |
| 4 | afterEach hook runs: cy.clearCookies() | Cookies cleared from browser | — | PASS |
| 5 | beforeEach hook runs again: cy.visit('https://example.cypress.io') | Browser reloads homepage | — | PASS |
| 6 | Test 2 runs: cy.get('button#login').should('be.visible') | Homepage loaded with login button visible | Login button with id 'login' is visible | PASS |
| 7 | afterEach hook runs again: cy.clearCookies() | Cookies cleared from browser | — | PASS |
beforeEach hook in Cypress testing?beforeEachbeforeEach hook runs before each test to prepare the environment or state needed for the test.afterEachafterEach, which runs after tests to clean up, beforeEach sets up conditions before tests.beforeEach = setup before tests [OK]afterEach in a Cypress test file?afterEach(() => { ... }).describe('My Tests', () => {
beforeEach(() => {
cy.visit('/login')
})
it('Test 1', () => {
cy.get('#username').type('user1')
})
it('Test 2', () => {
cy.get('#username').type('user2')
})
})cy.visit('/login') run when these tests execute?beforeEach behaviorbeforeEach hook runs before every individual test inside the describe block.cy.visit('/login') runs twice, once before each test.describe('Sample', () => {
beforeEach(() => {
cy.visit('/dashboard')
})
afterEach(() => {
cy.clearCookies
})
it('checks title', () => {
cy.title().should('include', 'Dashboard')
})
})cy.clearCookies not run after the test?afterEach hook codecy.clearCookies without parentheses, so the function is not called.cy.clearCookies().cy.clearCookies is missing parentheses to call the function -> Option AbeforeEach for setup (login) and afterEach for cleanup (clear local storage).beforeEach to log in and afterEach to clear local storage -> Option DPass the test and this pattern moves unknown