Cypress BeforeEach and AfterEach Hook

Profile picture for user arilio666

In this article, we will see how we can use the two hooks beforeEach and afterEach. Before we use them, let us know what they are.


  • beforeEach hook runs code before each test in a suite.
  • It is commonly used to set the environment before proceeding to the actual test.
  • Like a repeated thing we do before each test to start with.
  • Generally, logging in or creating data that a test depends upon comes here.


  • afterEach hook is opposite to what beforeEach hook does within it.
  • They are commonly used to clean up after a test, such as logging out, returning to the main page, or resetting the environment to its original state.


Let us automate the autopract site.

before hook - visit the URL
beforeEach hook - close popup
Test - add trimm dress to cart
afterEach hook - return to the main page
after hook - log that test has been completed

describe('Automate AutoPract',()=>{
   before(() => {
   it('Add Trim Dress To Cart',()=>{

       cy.log('Test Ended')
  •  As the popup occurs frequently, this is considered inside the beforeEach, which must be closed to start the test.
  • After adding to the cart, we must return to the main page.
  • This can be in the after each as it relates to resetting to the main page often.