Saltar a contenido

Cypress E2E Tests Documentation

Overview

This document describes the comprehensive End-to-End (E2E) testing suite implemented with Cypress for the OrthoPosture EPPA system. The tests validate the complete user workflow from marker capture to analysis export across all 4 views (Anterior, Posterior, Lateral Derecha, Lateral Izquierda).

Test Structure

Test Files

  1. 01-marker-capture.cy.ts - Marker Capture Workflow
  2. Tests the marker capture page functionality
  3. Validates image upload, marker placement, zoom/pan, and export

  4. 02-analysis-anterior.cy.ts - Vista Anterior Analysis

  5. Tests all 4 anterior regions (Cérvico-Cefálica, Tronco-Columna, Escapular, Pélvica-Inferior)
  6. Validates API integration and diagnostic results

  7. 03-analysis-posterior.cy.ts - Vista Posterior Analysis

  8. Tests all 4 posterior regions (Cérvico-Cefálica, Tronco-Columna, Pélvica, Pie-Tobillo)
  9. Validates coronal balance and calcaneo angle calculations

  10. 04-analysis-lateral.cy.ts - Vistas Laterales Analysis

  11. Tests both lateral views (Derecha and Izquierda)
  12. Validates lordosis measurements and angle calculations
  13. Common tests for zoom, pan, and export

  14. 05-integration.cy.ts - Complete End-to-End Integration

  15. Tests the full workflow from capture through all 4 analyses
  16. Error handling tests
  17. Validation tests for missing data

Setup and Installation

Prerequisites

  • Node.js 20+ installed
  • Next.js dev server running on port 9002
  • Python FastAPI server running on port 8000

Installation

# Install Cypress and dependencies
npm install --save-dev cypress @testing-library/cypress start-server-and-test

# Verify installation
npx cypress verify

Running Tests

Interactive Mode (Cypress Test Runner)

# Start servers and open Cypress Test Runner
npm run test:e2e:open

# Or manually:
# Terminal 1: Start Next.js
npm run dev

# Terminal 2: Start Python API
source venv/bin/activate
cd python && python api.py

# Terminal 3: Open Cypress
npx cypress open

Headless Mode (CI/CD)

# Run all tests headless
npm run test:e2e

# Or manually:
npx cypress run

# Run specific test file
npx cypress run --spec "cypress/e2e/01-marker-capture.cy.ts"

# Run with specific browser
npx cypress run --browser chrome

Available NPM Scripts

{
  "cypress:open": "cypress open",
  "cypress:run": "cypress run",
  "test:e2e": "start-server-and-test dev http://localhost:9002 cypress:run",
  "test:e2e:open": "start-server-and-test dev http://localhost:9002 cypress:open"
}

Test Data

Fixture Files

All test data is stored in cypress/fixtures/:

  • test-image.png - Test patient image (copy of analisis_anterior_2025-06-10.png)
  • markers-*.csv - Auto-generated marker CSV files for each test

Real MATLAB Coordinates

Tests use real patient marker coordinates extracted from MATLAB .mat files:

Vista Anterior Markers

Tragus Der.,A,420.38,554.05
Tragus Izq.,A,565.84,557.61
Eminencia Frontal Media,A,495.53,501.49
...

Vista Posterior Markers

Lóbulo Izq,P,422.50,562.73
Lóbulo Der,P,574.95,564.19
Cervical 7,P,499.82,652.90
...

Vista Lateral Derecha Markers

Tragus Der.,LD,435.87,544.13
Apex Cervical Der.,LD,355.74,636.31
Punto Acromion Der.,LD,389.30,715.85
...

Vista Lateral Izquierda Markers

Tragus Izq.,LI,530.02,536.21
Apex Cervical Izq.,LI,611.01,628.25
Punto Acromion Izq.,LI,540.15,716.68
...

Custom Cypress Commands

Located in cypress/support/commands.ts:

cy.uploadImage(fileName)

Uploads a test image from the fixtures directory.

cy.uploadImage('test-image.png');

cy.addMarker(canvasSelector, x, y, markerName?)

Adds a marker at specific canvas coordinates.

cy.addMarker('canvas', 500, 300, 'Tragus Der.');

cy.analyzeRegion(regionName)

Clicks the analysis button for a specific region.

cy.analyzeRegion('Cérvico-Cefálica');

Test Coverage

Marker Capture Tests (10 tests)

  1. Load page - Verifies page loads successfully
  2. Upload image - Tests image upload and canvas display
  3. Select view - Tests view type selection (Anterior, Posterior, etc.)
  4. Add markers - Tests marker placement with mouse clicks
  5. Zoom/Pan - Tests canvas zoom and pan functionality
  6. Delete marker - Tests marker deletion
  7. Export markers - Tests CSV/TSV export
  8. Complete workflow - Tests full marker capture workflow
  9. Pan by dragging - Tests image panning by drag
  10. State persistence - Tests session storage

Analysis Tests (per view)

Each analysis view (Anterior, Posterior, Lateral Derecha, Lateral Izquierda) tests:

  1. Load page - Verifies analysis page loads
  2. Region analysis - Tests each anatomical region (4 per view)
  3. Upload markers - Tests marker file upload
  4. API integration - Validates API calls and responses
  5. Results display - Verifies diagnostic results in table
  6. Export - Tests results export
  7. Zoom/Pan - Tests canvas operations during analysis
  8. Complete workflow - Tests full analysis workflow

Integration Tests (5 tests)

  1. Complete E2E workflow - Tests entire flow from capture to all 4 analyses
  2. Error handling - Tests API error responses
  3. Validation - Tests missing marker validation
  4. Zoom/Pan - Tests canvas operations across workflow
  5. Export all - Tests export from multiple views

Configuration

Cypress Config (cypress.config.ts)

export default defineConfig({
  e2e: {
    baseUrl: 'http://localhost:9002',  // Next.js dev server
    viewportWidth: 1920,
    viewportHeight: 1080,
    video: true,
    screenshotOnRunFailure: true,
    defaultCommandTimeout: 10000,
    requestTimeout: 10000,
    responseTimeout: 10000,
    env: {
      apiUrl: 'http://localhost:8000',  // Python FastAPI server
    },
  },
});

API Interception

Tests use cy.intercept() to validate backend API calls:

// Intercept anterior API calls
cy.intercept('POST', '**/api/anterior/**').as('anteriorApi');

// Analyze region
cy.contains('button', /Cérvico.*Cefálica/i).click();

// Wait for API response
cy.wait('@anteriorApi', { timeout: 10000 });

Test Strategies

Image Upload Strategy

Tests upload images using cy.selectFile():

cy.get('input[type="file"]').selectFile('cypress/fixtures/test-image.png', { force: true });
cy.wait(2000);  // Wait for image to load

Marker Upload Strategy

Tests dynamically create CSV files and upload them:

const markersContent = `marcador,vista,x,y
Tragus Der.,A,420.38,554.05
Tragus Izq.,A,565.84,557.61`;

cy.writeFile('cypress/fixtures/markers-test.csv', markersContent);
cy.get('input[type="file"][accept*="text"]').selectFile('cypress/fixtures/markers-test.csv');

Region Analysis Strategy

Tests analyze regions sequentially to avoid race conditions:

const regions = [/Cérvico.*Cefálica/i, /Tronco.*Columna/i];

regions.forEach((regionName) => {
  cy.contains('button', regionName).click();
  cy.wait('@anteriorApi', { timeout: 10000 });
  cy.wait(1000);  // Wait between analyses
});

Canvas Interaction Strategy

Tests use trigger() for canvas interactions:

// Zoom in
cy.get('canvas').trigger('wheel', { deltaY: -100 });

// Pan
cy.get('canvas')
  .trigger('mousedown', { clientX: 400, clientY: 300 })
  .trigger('mousemove', { clientX: 500, clientY: 400 })
  .trigger('mouseup');

Debugging

Screenshots and Videos

Cypress automatically captures: - Screenshots on test failure: cypress/screenshots/ - Videos of test runs: cypress/videos/

Viewing Test Results

# View last test run videos
open cypress/videos/

# View screenshots
open cypress/screenshots/

Debug Mode

// Add debug breakpoints
cy.debug();

// Pause test execution
cy.pause();

// Log to Cypress Command Log
cy.log('Debug message');

CI/CD Integration

GitHub Actions Example

name: E2E Tests

on: [push, pull_request]

jobs:
  cypress-run:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install Python dependencies
        run: |
          python -m venv venv
          source venv/bin/activate
          pip install -r requirements.txt

      - name: Setup Node
        uses: actions/setup-node@v3
        with:
          node-version: '20'

      - name: Install Node dependencies
        run: npm ci

      - name: Start Python API
        run: |
          source venv/bin/activate
          cd python && python api.py &
          sleep 5

      - name: Run Cypress tests
        uses: cypress-io/github-action@v6
        with:
          start: npm run dev
          wait-on: 'http://localhost:9002'
          wait-on-timeout: 120
          browser: chrome

      - name: Upload screenshots
        if: failure()
        uses: actions/upload-artifact@v3
        with:
          name: cypress-screenshots
          path: cypress/screenshots

      - name: Upload videos
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: cypress-videos
          path: cypress/videos

Known Issues and Workarounds

Issue 1: Page Load Timeout

Problem: Tests fail with "Timed out retrying after 10000ms"

Solution: Ensure both Next.js and Python API servers are running:

# Check servers
curl http://localhost:9002  # Next.js
curl http://localhost:8000/docs  # Python API

Issue 2: Canvas Not Visible

Problem: Canvas element not found or not visible

Solution: Add wait times after image upload:

cy.uploadImage('test-image.png');
cy.wait(2000);  // Wait for canvas to render
cy.get('canvas').should('be.visible');

Issue 3: Marker Selection Fails

Problem: Dropdown marker selection doesn't work

Solution: Use { force: true } option:

cy.contains(/Tragus/i).first().click({ force: true });

Issue 4: API Timeout

Problem: API calls timeout during test

Solution: Increase timeout in intercept:

cy.wait('@anteriorApi', { timeout: 15000 });

Best Practices

  1. Use Real Data: Always use real MATLAB coordinates for validation
  2. Wait Times: Add appropriate waits after async operations
  3. Isolation: Each test should be independent and idempotent
  4. Cleanup: Tests should clean up their data (if applicable)
  5. Descriptive Names: Use clear, descriptive test names
  6. API Mocking: Use intercepts to validate backend calls
  7. Assertions: Make specific assertions, not generic ones
  8. Screenshots: Leverage Cypress automatic screenshots on failure

Performance Considerations

  • Average test duration: ~10-15 seconds per test
  • Complete suite: ~5-8 minutes
  • Parallel execution: Not currently configured (can be added with Cypress Dashboard)

Future Enhancements

  1. Visual Regression Testing: Add cypress-image-snapshot for UI consistency
  2. Accessibility Testing: Add cypress-axe for a11y validation
  3. Code Coverage: Integrate @cypress/code-coverage for coverage reports
  4. Parallel Execution: Configure Cypress Dashboard for parallel test runs
  5. Mobile Testing: Add viewport tests for responsive design
  6. Performance Metrics: Add Lighthouse CI for performance monitoring

Resources

Support

For issues or questions: 1. Check test output in cypress/videos/ and cypress/screenshots/ 2. Review Cypress Command Log in Test Runner 3. Check browser console for errors 4. Verify servers are running correctly 5. Consult this documentation for known issues


Last Updated: 2025-10-07 Test Coverage: 45+ E2E tests across 5 test files Status: ✅ Complete and ready for execution