- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement hooks in Cypress?
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.