beforeEach and afterEach hooks in Cypress - Build an Automation Script
describe('Login and Logout Tests with beforeEach and afterEach', () => { beforeEach(() => { cy.visit('http://localhost:3000/login'); cy.get('[data-cy=username]').type('testuser'); cy.get('[data-cy=password]').type('Test@1234'); cy.get('[data-cy=login-button]').click(); cy.url().should('include', '/dashboard'); }); afterEach(() => { cy.get('[data-cy=logout-button]').click(); cy.url().should('include', '/login'); }); it('should display dashboard content', () => { cy.get('[data-cy=welcome-message]').should('contain.text', 'Welcome, testuser'); }); it('should allow access to profile page', () => { cy.get('[data-cy=profile-link]').click(); cy.url().should('include', '/profile'); cy.get('[data-cy=profile-header]').should('contain.text', 'Your Profile'); }); });
The beforeEach hook runs before every test. It visits the login page, enters the username and password, clicks login, and verifies the dashboard URL. This ensures each test starts with a logged-in user.
The afterEach hook runs after every test. It clicks the logout button and verifies the URL returns to the login page. This cleans up the session so tests do not affect each other.
Each test then assumes the user is logged in and can perform actions like checking the welcome message or navigating to the profile page.
Selectors use data-cy attributes for clarity and stability. Assertions check URLs and visible text to confirm correct navigation and page content.
Now add data-driven testing with 3 different user credentials to verify login works for all