0
0
Cypresstesting~8 mins

beforeEach and afterEach hooks in Cypress - Framework Patterns

Choose your learning style9 modes available
Framework Mode - beforeEach and afterEach hooks
Folder Structure
  cypress/
  ├── e2e/
  │   ├── login.spec.js       # Test files using beforeEach and afterEach hooks
  │   └── dashboard.spec.js
  ├── support/
  │   ├── commands.js         # Custom commands
  │   └── e2e.js              # Global beforeEach/afterEach can be placed here
  ├── fixtures/
  │   └── user.json           # Test data
  cypress.config.js            # Configuration file
  
Test Framework Layers
  • Test Files (cypress/e2e/): Contains test cases where beforeEach and afterEach hooks run setup and cleanup before and after each test.
  • Support Layer (cypress/support/): Contains reusable commands and global hooks that run before or after all tests or suites.
  • Fixtures (cypress/fixtures/): Holds test data files loaded during tests.
  • Configuration (cypress.config.js): Defines environment settings, base URLs, and browser options.
Configuration Patterns

Use cypress.config.js to define environment variables and base URLs for different environments (dev, staging, prod).

Example snippet:

  import { defineConfig } from 'cypress'

  export default defineConfig({
    e2e: {
      baseUrl: 'https://example.com',
      env: {
        username: 'testuser',
        password: 'password123'
      },
      setupNodeEvents(on, config) {
        // implement node event listeners here
      }
    }
  })
  

Access credentials in tests via Cypress.env('username').

Test Reporting and CI/CD Integration
  • Use built-in Cypress reporter or integrate with mochawesome for detailed HTML reports.
  • Configure CI pipelines (GitHub Actions, Jenkins, GitLab CI) to run npx cypress run on code push.
  • Store test artifacts like screenshots and videos for failed tests automatically.
  • Use beforeEach and afterEach hooks to prepare and clean test state for reliable CI runs.
Best Practices
  1. Use beforeEach to set up test state: Reset app state, visit pages, or login before each test to keep tests independent.
  2. Use afterEach for cleanup: Clear cookies, local storage, or reset mocks to avoid test pollution.
  3. Keep hooks simple and fast: Avoid heavy operations in hooks to keep tests quick and stable.
  4. Use global hooks in cypress/support/e2e.js for common setup: For example, global login or clearing data before all tests.
  5. Do not share state between tests: Each test should be able to run alone without relying on previous tests.
Self Check

Where would you add a beforeEach hook that logs in a user before every test in the login.spec.js file?

Key Result
Use beforeEach and afterEach hooks in Cypress tests to set up and clean test state for reliable, independent tests.