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:

  • 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:

  • 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.

Example:

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(() => {
       cy.visit('http://www.autopract.com/#/home/fashion')
       
       
   })
   beforeEach(function(){
       cy.get('.close').as('Popup')
       cy.get('@Popup').click()
   })
   
   it('Add Trim Dress To Cart',()=>{
       cy.xpath('/html/body/app-root/app-fashion-one/section[3]/div/div/div/owl-carousel-o/div/div[1]/owl-stage/div/div/div[1]/div/app-product-box-one/div/div[1]/div[2]/a/img').click()

   })
   afterEach(function(){
       cy.get('#headerlogo').click()
   })
   after(function(){
       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.