describe('Test Suite', () => { beforeEach(() => { cy.log('beforeEach hook'); }); afterEach(() => { cy.log('afterEach hook'); }); it('Test 1', () => { cy.log('Test 1 body'); }); it('Test 2', () => { cy.log('Test 2 body'); }); });
The beforeEach hook runs before every test, and afterEach runs after every test. So for two tests, the order is: beforeEach, test body, afterEach, then repeat for the second test.
Assertions about the UI element's visibility should be in beforeEach to confirm it's ready before tests. Cleanup assertions belong in afterEach to confirm the element is removed after tests.
afterEach hook is not running after the first test but runs after the second test. What is the most likely cause?If a test has asynchronous commands but does not return or await them properly, Cypress may not detect test completion correctly, causing hooks like afterEach to run late or out of order.
cy.login() and cy.logout(). Which setup is correct?describe('User tests', () => { beforeEach(() => { cy.login(); }); afterEach(() => { cy.logout(); }); it('checks dashboard', () => { cy.get('#dashboard').should('be.visible'); }); });
Using cy.login() in beforeEach ensures the user is logged in before every test. Using cy.logout() in afterEach ensures cleanup after each test. This is the recommended pattern.
describe('Outer Suite', () => { beforeEach(() => cy.log('Outer beforeEach')); afterEach(() => cy.log('Outer afterEach')); describe('Inner Suite', () => { beforeEach(() => cy.log('Inner beforeEach')); afterEach(() => cy.log('Inner afterEach')); it('Inner test', () => cy.log('Test body')); }); });
For nested describes, beforeEach hooks run from outer to inner before the test. afterEach hooks run from inner to outer after the test. So the order is: Outer beforeEach, Inner beforeEach, Test, Inner afterEach, Outer afterEach.