0
0
Cypresstesting~8 mins

Component test setup in Cypress - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Component test setup
Folder Structure
  cypress/
  ├── e2e/                  # End-to-end tests
  ├── component/            # Component tests
  │   ├── Button.cy.js      # Example component test file
  │   └── Header.cy.js
  ├── support/              # Support files and commands
  │   ├── commands.js       # Custom commands
  │   └── component.js      # Component test support setup
  ├── fixtures/             # Test data files
  └── cypress.config.js     # Cypress configuration file
  
Test Framework Layers
  • Component Tests: Located in cypress/component/, these test individual UI components in isolation.
  • Support Layer: cypress/support/component.js sets up the environment for component testing, including mounting utilities.
  • Fixtures: Static test data stored in cypress/fixtures/ to keep tests clean and reusable.
  • Configuration: cypress.config.js defines environment settings, test types, and component testing options.
Configuration Patterns

Use cypress.config.js to configure component testing:

  import { defineConfig } from 'cypress'

  export default defineConfig({
    component: {
      devServer: {
        framework: 'react',
        bundler: 'webpack'
      },
      supportFile: 'cypress/support/component.js'
    },
    env: {
      baseUrl: 'http://localhost:3000',
      apiUrl: 'https://api.example.com'
    },
    retries: 1
  })
  

Use environment variables for URLs and credentials to keep tests flexible across environments.

Test Reporting and CI/CD Integration
  • Use Cypress built-in reporters like spec or integrate with mochawesome for detailed HTML reports.
  • Configure CI pipelines (GitHub Actions, GitLab CI, Jenkins) to run cypress run --component for component tests.
  • Save test artifacts like screenshots and videos on failure for debugging.
  • Fail the build if any component test fails to ensure quality.
Best Practices
  1. Isolate Components: Test components independently without relying on the full app to catch issues early.
  2. Use Support Files: Centralize mounting logic and custom commands in support/component.js for reuse.
  3. Keep Tests Small: Write focused tests for one component behavior at a time.
  4. Mock External Calls: Avoid real network calls by stubbing APIs to keep tests fast and reliable.
  5. Use Fixtures: Store test data separately to keep tests clean and easy to update.
Self Check

Where in this folder structure would you add a new component test file for a LoginForm component?

Key Result
Organize component tests in a dedicated folder with support files and config for isolated, fast UI testing.