Hooks in Cypress

Introduction 

Hooks that are used in cypress are- ‘beforeEach’, ‘afterEach’, ‘before’, and ‘after’. These hooks are borrowed from the Mocha Framework. The primary purpose of using hooks is to have an organized test.

The “beforeEach” hook is used when we want to execute a particular set of steps before the completion of each test case in our test file. The “afterEach” hook is used when we want to execute a particular set of steps after the completion of each test case in our test file. The “before” hook is used when we want to execute particular steps before the completion of all the test cases in our test file. And the “after” hook is used when we want to execute a particular set of steps after the completion of all the test cases in our test file. Using hooks helps in reducing the repetition of test steps in our test file and makes our code optimized.  

In this blog, we will discuss- 

  • Project setup for using hooks in cypress 
  • How to create hooks 

Project setup for using Hooks in Cypress

Firstly, we must install all prerequisites in our project. (For more info about prerequisites you can visit- API Automation testing using Cypress with javascript )

After verifying the prerequisites, create a new project folder in order to set up a new Cypress project.

–Create the folder in any location of your system and open it in Visual Studio Code by selecting File>Open Folder>Choose file from system>click Ok 

Hooks in cypress

Next, we need to run the ‘npm init –y’ command in the terminal to create a ‘package.json’ file in our project which will be used as a dependency management file and is used in initializing the npm project by allowing us to run the npm commands directly on the project.  

Hooks in Cypress

The ‘package.json’ file includes the name of the project, the version, the description for the project, keywords, author, license, and script section which will be used to run the test scripts from the terminal. 

After the creation of the ‘package.json’ file, install cypress by passing the ‘npm install cypress’ command to install the latest version of cypress or ‘npm install cypress@version number’ to install the required version of cypress, e.g., ‘npm install cypress@10.10.  

Install Cypress

After installing Cypress we can check the cypress version by using ‘npx cypress -v’ command.

Cypress version

In order to open Cypress, we need to run ‘npx cypress open’ command which will provide the GUI of Cypress after which we need to Select E2E Testing> click on Continue> choose a browser> click on Start E2E Testing in the selected browser.

Choose a browser

After clicking on the start E2E testing we get a cypress runner where we can create our spec files with ‘.cy.js’ extension and this file will also be created in VS code in which we can write our test case 

Hooks in Cypress
Hooks in Cypress

How to Create Hooks in Cypress

Given below is an example for a better understanding of how we can use Hooks in our test:

 Test case: 

  • Step 2: Click on login link 
  • Step 3: Enter username 
  • Step 4: Enter password 
  • Step 5: Click login button 
  • Step 6: Validate that the page contains the expected title 
  • Step 7: Logout 

Test 1: Using Hooks for a single test case 

/// <reference types="cypress" /> 
import * as Credentials from '../fixtures/example'; 
describe('My first test', function() 
{ 
before(() => { 
cy.visit('https://automationteststore.com/') 
cy.get('#customer_menu_top').click() 
cy.get('#loginFrm_loginname').type(Credentials.username) 
cy.get('#loginFrm_password').type(Credentials.password) 
cy.get('button[type="submit"][title="Login"]').click() 
}) 
beforeEach(() => { 
cy.log('Test case execution has started') 
}) 
afterEach(() => { 
cy.log('Test case execution has ended') 
}) 
after(() => { 
cy.get('.side_account_list > :nth-child(10) > a').click() 
}) 
it('Validate that the page contains the expected title', function() 
{ 
cy.get('.maintext').should('contain',' My Account') 
}) 
}) 
Hooks in Cypress code

Code explanation: 

In the above test file, we have created a single test case that will validate if the page contains the expected title, and provided hooks to the test. The “before” hook contains steps to visit the required link of the page, provide the login credentials, and log in to the website. The “beforeEach” hook contains text that will be printed before the test case or we can also add the other steps that we want to perform on the web page before each test case. The “afterEach” hook contains a text that will be printed after the test case or we can also add the other steps that we want to perform on the web page after each test case. Lastly, the “after” hook contains a step to log off from the website.  

Execution: 

In order to execute the test file, we need to open the Cypress test runner using ‘npx cypress open’ command and click on the test file on the test runner, after which the execution will be started and the results for the test will be displayed as shown in the image below:

Test 2: Using hooks for multiple test cases 

/// <reference types="cypress" /> 
import * as Credentials from '../fixtures/example'; 
describe('My first test', function() 
{ 
before(() => { 
cy.visit('https://automationteststore.com/')  
}) 
beforeEach(() => { 
cy.log('Test case execution has started') 
}) 
afterEach(() => { 
cy.log('Test case execution has ended') 
}) 
after(() => { 
cy.get('.side_account_list > :nth-child(10) > a').click() 
}) 
 
 
it('login to the website', function() 
{ 
cy.get('#customer_menu_top').click() 
cy.get('#loginFrm_loginname').type(Credentials.username) 
cy.get('#loginFrm_password').type(Credentials.password) 
cy.get('button[type="submit"][title="Login"]').click() 
}) 
it('Validate that the page contains the expected title', function() 
{ 
cy.get('.maintext').should('contain',' My Account') 
}) 
}) 
Hooks in Cypress code

Code explanation: 

In the above test file, we have created two test cases, the first test case contains the steps to log in to the website and the second test will validate if the page contains the expected title. similarly, we can create more test cases with different steps to be performed on the website. The “before” hook contains steps to visit the required link of the page where we need to provide the login credentials and login to the website. The “beforeEach” hook contains text that will be printed before each of the test cases. The “afterEach” hook contains a text that will be printed after each of the test case and lastly, the “after” hook contains steps to log off from the website. 

Execution: 

After executing the above test file, we get the results as shown in the image below: 

Conclusion: 

In this blog, we went through examples of creating hooks in our test file. The first test example contains one test case and the second test example is a modification of the first test example where we added an additional test case and made use of hooks in a much better way. Hooks are useful when we have a set of pre-condition or post-condition test steps that occur repeatedly for all the test cases either before or after each of them and also when we have pre-condition or post-condition test steps that need to be executed once before all the tests cases or once after all the test cases. Hence hooks should be used when we have multiple test cases and when all of the test cases have common steps to be executed before and after them.