Life Cycle Hooks in Cypress

Jul 16, 2024

Life Cycle Hooks in Cypress

Overview

  • Lifecycle hooks in Cypress help reduce code redundancy and promote code reuse in each spec file.
  • There are four main lifecycle hooks in Cypress: before, beforeEach, afterEach, and after.

Lifecycle Hooks

  • before:
    • Executed once per spec file.
  • beforeEach:
    • Executed before every test case.
  • afterEach:
    • Executed after every test case.
  • after:
    • Executed once per spec file.

Implementing Lifecycle Hooks

  1. Create a spec file, e.g., life_cycle_hooks.cy.js.
  2. Use describe to define a test suite.
  3. Implement hooks within the test suite:
    • before:
      before(() => {
        cy.log('This lifecycle hook will be executed once before all tests in the spec file');
      });
      
    • beforeEach:
      beforeEach(() => {
        cy.log('This lifecycle hook will be executed before each test case');
      });
      
    • afterEach:
      afterEach(() => {
        cy.log('This lifecycle hook will be executed after each test case');
      });
      
    • after:
      after(() => {
        cy.log('This lifecycle hook will be executed once after all tests in the spec file');
      });
      

Example Scenario

Test Cases

  • Test Case 1:
    it('Test Case 1', () => {
      cy.visit('/');
      cy.get('input[name=username]').type('admin');
      cy.get('input[name=password]').type('password');
      cy.get('form').submit();
    });
    
  • Test Case 2:
    it('Test Case 2', () => {
      cy.visit('/');
      cy.get('input[name=username]').type('admin');
      cy.get('input[name=password]').type('password');
      cy.get('form').submit();
    });
    

Execution Flow

  • Before Hook: Executed once before all tests.
  • Before Each Hook: Executed twice (once before each test case).
  • Test Cases: Executed sequentially.
  • After Each Hook: Executed twice (once after each test case).
  • After Hook: Executed once after all tests.

Conclusion

  • Use before to run code once before all tests in a spec file.
  • Use beforeEach to run code before each test case.
  • Use afterEach to run code after each test case.
  • Use after to run code once after all tests in a spec file.
  • These hooks help organize setup and teardown code, ensuring efficient tests with minimal redundancy.