0
0
Cypresstesting~8 mins

Preserving state between tests in Cypress - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Preserving state between tests
Folder Structure
cypress/
├── e2e/                  # Test specs
│   ├── login.cy.js       # Login tests
│   ├── dashboard.cy.js   # Dashboard tests
│   └── ...
├── fixtures/             # Test data files (JSON, etc.)
│   └── user.json
├── support/              # Support files
│   ├── commands.js       # Custom commands (e.g., login)
│   ├── e2e.js            # Global setup for tests
│   └── index.js          # Support index
cypress.config.js         # Cypress configuration file
Test Framework Layers
  • Test Specs (cypress/e2e): Actual test files where tests run. Use describe and it blocks.
  • Support Layer (cypress/support): Contains reusable commands and global setup. For preserving state, use commands.js to create login commands and e2e.js to handle state preservation.
  • Fixtures (cypress/fixtures): Store test data like user credentials to keep tests clean and maintainable.
  • Configuration (cypress.config.js): Define base URLs, environment variables, and test settings.
Configuration Patterns
  • Environment Variables: Use cypress.env.json or cypress.config.js to store sensitive data like usernames and passwords securely.
  • Base URL: Set baseUrl in cypress.config.js for easy URL management.
  • Preserving State: Use cy.session() to cache login sessions between tests, avoiding repeated logins and speeding up tests.
  • Custom Commands: Define login commands in commands.js to reuse login logic and integrate cy.session() inside.
Test Reporting and CI/CD Integration
  • Test Reports: Use Cypress built-in reporter or integrate with tools like Mochawesome for detailed HTML reports.
  • CI/CD: Integrate Cypress tests in pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests on every code push.
  • State Preservation Impact: Preserving state reduces test run time, making CI pipelines faster and more efficient.
  • Artifacts: Save screenshots and videos on test failures for easier debugging.
Best Practices for Preserving State Between Tests
  1. Use cy.session() to cache login sessions: This avoids logging in before every test, saving time and reducing flakiness.
  2. Keep tests independent: Even with preserved state, each test should not rely on others to pass.
  3. Use custom commands: Encapsulate login and session logic in commands for reuse and clarity.
  4. Clear state only when needed: Reset cookies or local storage between tests if tests require a clean state.
  5. Store sensitive data securely: Use environment variables or fixtures, never hardcode credentials in tests.
Self Check

Where in this framework structure would you add a new custom command to preserve user login state across tests?

Key Result
Use cy.session() with custom commands in support/commands.js to preserve login state between Cypress tests.