0
0
Cypresstesting~15 mins

beforeEach and afterEach hooks in Cypress - Build an Automation Script

Choose your learning style9 modes available
Test login and logout using beforeEach and afterEach hooks
Preconditions (2)
Step 1: Open the login page
Step 2: Enter 'testuser' in the username field
Step 3: Enter 'Test@1234' in the password field
Step 4: Click the login button
Step 5: Verify that the dashboard page is displayed
Step 6: Perform any test actions on the dashboard
Step 7: Click the logout button
Step 8: Verify that the login page is displayed again
✅ Expected Result: User is logged in before each test and logged out after each test, ensuring tests start with a fresh session
Automation Requirements - Cypress
Assertions Needed:
Verify URL contains '/dashboard' after login
Verify URL contains '/login' after logout
Best Practices:
Use beforeEach hook to perform login before each test
Use afterEach hook to perform logout after each test
Use Cypress commands and assertions consistently
Use clear and maintainable selectors (e.g., data-cy attributes)
Automated Solution
Cypress
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.

Common Mistakes - 4 Pitfalls
Not using beforeEach to login, repeating login steps in every test
Not using afterEach to logout, causing session state to leak between tests
Using brittle selectors like CSS classes that may change
Not waiting or asserting URL changes after login/logout
Bonus Challenge

Now add data-driven testing with 3 different user credentials to verify login works for all

Show Hint