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
Practice
beforeEach hook in Cypress testing?Solution
Step 1: Understand the role of
ThebeforeEachbeforeEachhook runs before each test to prepare the environment or state needed for the test.Step 2: Differentiate from
UnlikeafterEachafterEach, which runs after tests to clean up,beforeEachsets up conditions before tests.Final Answer:
To run code before every test to set up the test environment -> Option AQuick Check:
beforeEach= setup before tests [OK]
- Confusing beforeEach with afterEach
- Thinking beforeEach skips tests
- Assuming beforeEach groups tests
afterEach in a Cypress test file?Solution
Step 1: Recall correct function syntax in Cypress
Cypress hooks use function calls with arrow functions inside parentheses, likeafterEach(() => { ... }).Step 2: Identify syntax errors in other options
Options B, C, and D miss parentheses or use incorrect arrow function syntax.Final Answer:
afterEach(() => { cy.visit('/home') }) -> Option BQuick Check:
Hook syntax = function call with arrow function [OK]
- Omitting parentheses after hook name
- Using curly braces without parentheses
- Incorrect arrow function syntax
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?Solution
Step 1: Understand
ThebeforeEachbehaviorbeforeEachhook runs before every individual test inside thedescribeblock.Step 2: Count the tests and hook calls
There are two tests, socy.visit('/login')runs twice, once before each test.Final Answer:
Twice, once before each test -> Option CQuick Check:
beforeEach runs before every test [OK]
- Thinking beforeEach runs only once
- Confusing beforeEach with afterEach
- Assuming hooks run after tests
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?Solution
Step 1: Check the
The code usesafterEachhook codecy.clearCookieswithout parentheses, so the function is not called.Step 2: Understand function call syntax
To execute the command, parentheses are required:cy.clearCookies().Final Answer:
Becausecy.clearCookiesis missing parentheses to call the function -> Option AQuick Check:
Functions need () to run [OK]
- Forgetting parentheses on Cypress commands
- Confusing beforeEach and afterEach roles
- Assuming afterEach runs before tests
Solution
Step 1: Identify setup and cleanup tasks
Logging in is setup needed before each test; clearing local storage is cleanup after each test.Step 2: Assign tasks to correct hooks
UsebeforeEachfor setup (login) andafterEachfor cleanup (clear local storage).Final Answer:
UsebeforeEachto log in andafterEachto clear local storage -> Option DQuick Check:
Setup beforeEach, cleanup afterEach [OK]
- Mixing setup and cleanup in wrong hooks
- Using only one hook for both tasks
- Not cleaning up after tests
Ready to prove it?
Pass the test and this pattern moves unknown
