Bird
Raised Fist0
Cypresstesting~15 mins

beforeEach and afterEach hooks in Cypress - Build an Automation Script

Choose your learning style10 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

Practice

(1/5)
1. What is the main purpose of the beforeEach hook in Cypress testing?
easy
A. To run code before every test to set up the test environment
B. To run code after every test to clean up the test environment
C. To skip a test conditionally
D. To group multiple tests together

Solution

  1. Step 1: Understand the role of beforeEach

    The beforeEach hook runs before each test to prepare the environment or state needed for the test.
  2. Step 2: Differentiate from afterEach

    Unlike afterEach, which runs after tests to clean up, beforeEach sets up conditions before tests.
  3. Final Answer:

    To run code before every test to set up the test environment -> Option A
  4. Quick Check:

    beforeEach = setup before tests [OK]
Hint: Remember: beforeEach runs before tests, afterEach runs after [OK]
Common Mistakes:
  • Confusing beforeEach with afterEach
  • Thinking beforeEach skips tests
  • Assuming beforeEach groups tests
2. Which of the following is the correct syntax to use afterEach in a Cypress test file?
easy
A. afterEach { cy.visit('/home') }
B. afterEach(() => { cy.visit('/home') })
C. afterEach: () => cy.visit('/home')
D. afterEach => { cy.visit('/home') }

Solution

  1. Step 1: Recall correct function syntax in Cypress

    Cypress hooks use function calls with arrow functions inside parentheses, like afterEach(() => { ... }).
  2. Step 2: Identify syntax errors in other options

    Options B, C, and D miss parentheses or use incorrect arrow function syntax.
  3. Final Answer:

    afterEach(() => { cy.visit('/home') }) -> Option B
  4. Quick Check:

    Hook syntax = function call with arrow function [OK]
Hint: Hooks need parentheses and arrow functions: hook(() => {}) [OK]
Common Mistakes:
  • Omitting parentheses after hook name
  • Using curly braces without parentheses
  • Incorrect arrow function syntax
3. Consider this Cypress test code:
describe('My Tests', () => {
  beforeEach(() => {
    cy.visit('/login')
  })

  it('Test 1', () => {
    cy.get('#username').type('user1')
  })

  it('Test 2', () => {
    cy.get('#username').type('user2')
  })
})

How many times will cy.visit('/login') run when these tests execute?
medium
A. Once before all tests
B. Twice, once after each test
C. Twice, once before each test
D. Once after all tests

Solution

  1. Step 1: Understand beforeEach behavior

    The beforeEach hook runs before every individual test inside the describe block.
  2. Step 2: Count the tests and hook calls

    There are two tests, so cy.visit('/login') runs twice, once before each test.
  3. Final Answer:

    Twice, once before each test -> Option C
  4. Quick Check:

    beforeEach runs before every test [OK]
Hint: Count tests; beforeEach runs before each one [OK]
Common Mistakes:
  • Thinking beforeEach runs only once
  • Confusing beforeEach with afterEach
  • Assuming hooks run after tests
4. You wrote this Cypress test:
describe('Sample', () => {
  beforeEach(() => {
    cy.visit('/dashboard')
  })

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

  it('checks title', () => {
    cy.title().should('include', 'Dashboard')
  })
})

Why does cy.clearCookies not run after the test?
medium
A. Because cy.clearCookies is missing parentheses to call the function
B. Because afterEach only runs before tests
C. Because cy.clearCookies is not a valid Cypress command
D. Because beforeEach overrides afterEach

Solution

  1. Step 1: Check the afterEach hook code

    The code uses cy.clearCookies without parentheses, so the function is not called.
  2. Step 2: Understand function call syntax

    To execute the command, parentheses are required: cy.clearCookies().
  3. Final Answer:

    Because cy.clearCookies is missing parentheses to call the function -> Option A
  4. Quick Check:

    Functions need () to run [OK]
Hint: Always add () to call Cypress commands [OK]
Common Mistakes:
  • Forgetting parentheses on Cypress commands
  • Confusing beforeEach and afterEach roles
  • Assuming afterEach runs before tests
5. You want to test a form that requires logging in before each test and clearing local storage after each test. Which is the best way to organize your Cypress hooks?
hard
A. Use only beforeEach for both login and clearing local storage
B. Use afterEach to log in and beforeEach to clear local storage
C. Use only afterEach for both login and clearing local storage
D. Use beforeEach to log in and afterEach to clear local storage

Solution

  1. Step 1: Identify setup and cleanup tasks

    Logging in is setup needed before each test; clearing local storage is cleanup after each test.
  2. Step 2: Assign tasks to correct hooks

    Use beforeEach for setup (login) and afterEach for cleanup (clear local storage).
  3. Final Answer:

    Use beforeEach to log in and afterEach to clear local storage -> Option D
  4. Quick Check:

    Setup beforeEach, cleanup afterEach [OK]
Hint: Setup in beforeEach, cleanup in afterEach [OK]
Common Mistakes:
  • Mixing setup and cleanup in wrong hooks
  • Using only one hook for both tasks
  • Not cleaning up after tests
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard