0
0
Cypresstesting~8 mins

Value and attribute assertions in Cypress - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Value and attribute assertions
Folder Structure
  cypress/
  ├── e2e/
  │   ├── valueAttributeAssertions.spec.js  <-- Test files with value and attribute assertions
  │   └── otherTests.spec.js
  ├── fixtures/
  │   └── example.json  <-- Test data for assertions
  ├── support/
  │   ├── commands.js  <-- Custom commands for assertions
  │   └── e2e.js  <-- Global setup
  └── cypress.config.js  <-- Configuration for browsers, baseUrl
  
Test Framework Layers
  • Test Layer: Contains test specs that perform value and attribute assertions using Cypress commands like should('have.value') and should('have.attr').
  • Support Layer: Holds reusable custom commands and global setup to simplify assertion code and maintain consistency.
  • Fixtures Layer: Stores test data such as expected values or attribute names to keep tests clean and data-driven.
  • Configuration Layer: Manages environment settings, browser options, and base URLs for running tests in different contexts.
Configuration Patterns

Use cypress.config.js to define:

  • Base URL: Set baseUrl for the application under test to avoid repeating URLs in tests.
  • Environment Variables: Use env to store credentials or expected attribute values securely.
  • Browser Selection: Use CLI options like --browser chrome for cross-browser testing.

Example snippet from cypress.config.js:

  export default defineConfig({
    e2e: {
      baseUrl: 'https://example.com',
      env: {
        expectedInputValue: 'Hello Cypress',
        expectedButtonType: 'submit'
      }
    }
  })
  
Test Reporting and CI/CD Integration
  • Use Cypress built-in reporter for clear pass/fail results of value and attribute assertions.
  • Integrate with CI tools like GitHub Actions or Jenkins to run tests on every code push.
  • Generate HTML or JSON reports using plugins like mochawesome for detailed assertion outcomes.
  • Fail tests immediately on assertion failure to catch UI issues early.
Best Practices
  1. Use explicit assertions: Always assert specific values or attributes to verify UI correctness clearly.
  2. Keep selectors stable: Use data-* attributes for locating elements to avoid flaky tests.
  3. Reuse test data: Store expected values in fixtures or environment variables to avoid hardcoding.
  4. Write clear error messages: Use should with descriptive messages to understand failures quickly.
  5. Run tests in isolation: Each test should set up its own state to avoid dependencies affecting assertions.
Self Check

Where in this folder structure would you add a new custom command to assert that an input field has a specific placeholder attribute?

Key Result
Organize Cypress tests with clear folder layers, config for environments, and explicit value and attribute assertions for reliable UI validation.