What are Hooks in Cypress?
Cypress Hooks are used to carry out the certain operations prior/post every/each test.Some of the common hooks are as follows −
- before − It is executed, once the prior execution of any tests within a describe block is carried out.
- after − It is executed, once the post execution of all the tests within a describe block is carried out.
- beforeEach − It is executed prior to the execution of an individual, it blocks within a describe block.
- afterEach − It is executed post execution of the individual, it blocks within a describe block.
Implementation
The implementation of commands for the Cypress Hooks is explained below −
describe('Hooks and Tags in Cypress',function(){ before(function(){ // executes once prior to the all tests in it block cy.log("This is Before Hook") }) after(function(){ cy.log("This is my After Activity") }) beforeEach(function(){ cy.log('This is my Before Each Method') }) afterEach(function(){ cy.log("This should print at the end of Each Test Case") }) it('Hooks in Cypress',function(){ cy.log('This is my First Test Case') }) it('Hooks in Cypress',function(){ cy.log('This is my Second Test Case') }) it('Hooks in Cypress',function(){ cy.log('This is my 3rd Test Case') }) })
Execution Results
The output is mentioned below −
The output logs show that the first executed step is the BEFORE ALL.
The last executed step is the AFTER ALL. Both of them ran only once.
The step executed under BEFORE EACH ran twice (before each TEST BODY).
Also, step executed under AFTER EACH ran twice (after each TEST BODY).
Both the it blocks are executed in order, in which they are implemented.
Leave a comment