Cypress Hooks are used to carrying out 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('Adglob', 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 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, the step executed under AFTER EACH ran twice (after each TEST BODY).
Both blocks are executed in the order, in which they are implemented.
TAG
Apart from hooks, Cypress has tags – .only and .skip.
While the .only tag is utilized to execute it block to which it is tagged, the .skip tag is utilized to exclude it block to which it is tagged.
Implementation with .only
The implementation of the .only tag in Cypress is as follows −
describe('Adglob', function()
//it block with tag .only
it.only('First Test', function() {
cy.log("First Test")
})
//it block with tag .only
It.only('Second Test', function() {
cy.log("Second Test")
})
it('Third Test', function() {
cy.log("Third Test")
})
})
Execution Results
The output is given below −
The output logs show that it blocks (First and Second Test) with the .only tags only got executed.
Implementation with .skip
The implementation of the .skip tag in Cypress is as follows −
describe('Adglob', function()
it('First Test', function() {
cy.log("First Test")
})
it('Second Test', function() {
cy.log("Second Test")
})
//it block with tag .skip
it.skip('Third Test', function() {
cy.log("Third Test")
})
})
Execution Results
The output is as follows −
The output logs show that it block (Third Test) with the .skip tag got skipped from the execution.