How to implement hooks in Cypress?

Rest AssuredCypressDynamic Programming

We can implement hooks in Cypress. Cypress Hooks are used to carrying out certain operations prior/post every/each test. Some of the common hooks are −

  • before – Executes once prior execution any tests within a describe block.

  • after – Executes once post-execution all tests within a describe block.

  • beforeEach – Executes prior execution of the individual it blocks within a describe block.

  • afterEach – Executes post-execution of the individual it blocks within a describe block.

Example

Implementation

describe('Tutorialspoint', function() {
   before(function() {

      // executes once prior all tests in it block
      cy.log("Before hook")
   })
   after(function() {

      // executes once post all tests in it block
      cy.log("After hook")
   })
   beforeEach(function() {

      // executes prior each test within it block
      cy.log("BeforeEach hook")
   })
   afterEach(function() {

      // executes post each test within it block
      cy.log("AfterEac hook")
      })
   it('First Test', function() {
      cy.log("First Test")
   })
   it('Second Test', function() {
      cy.log("Second Test")
   })
})

Execution Results

The output logs show that the first executed step is the BEFORE ALL. Also, 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, the step executed under AFTER EACH ran twice (after each TEST BODY). Both it blocks are executed in the order in which they are implemented.

raja
Updated on 19-Nov-2021 10:40:03

Advertisements