# jam-ui Testing Implementation Approach

## How I Will Achieve the Goal

### Overview

You've asked me to verify that jam-ui conforms to the legacy app's API request/response sequence, patterns, and timings by creating comprehensive tests. Here's my structured approach:

## 🎯 Main Objectives

1. **API Sequence Verification** - Ensure jam-ui makes identical API calls as legacy app
2. **UI Testing** - Test all components function correctly
3. **E2E Testing** - Verify complete user journeys work end-to-end
4. **Comparison Analysis** - Generate reports showing conformance

## 📋 Implementation Strategy

### Phase 1: Test Infrastructure Setup

**What I'll Create:**
```
test/
├── utils/
│   ├── api-interceptor.ts          # Intercept & record API calls
│   ├── websocket-monitor.ts        # Monitor WebSocket connections
│   ├── sequence-comparator.ts      # Compare API sequences
│   └── test-helpers.ts              # Shared test utilities
├── fixtures/
│   ├── legacy-sequences/            # Copied from verification
│   │   ├── login-sequence.json
│   │   ├── session-creation-sequence.json
│   │   └── session-join-sequence.json
│   ├── users.json                   # Test user data
│   └── sessions.json                # Test session data
```

**Purpose:** Reusable infrastructure for all tests

---

### Phase 2: API Verification Tests

**What I'll Create:**
```
test/api-verification/
├── login-api.spec.ts
├── session-creation-api.spec.ts
└── session-join-api.spec.ts
```

**How They Work:**

```typescript
// Example: login-api.spec.ts
test('jam-ui login API sequence matches legacy', async ({ page }) => {
  const apiCalls = [];

  // Intercept all API requests
  page.on('request', req => {
    if (req.url().includes('/api/')) {
      apiCalls.push({
        method: req.method(),
        url: req.url(),
        timestamp: Date.now()
      });
    }
  });

  // Perform login on jam-ui
  await page.goto('http://beta.jamkazam.local:4000/');
  await page.fill('[name="email"]', 'nuwan@jamkazam.com');
  await page.fill('[name="password"]', 'jam123');
  await page.click('button[type="submit"]');
  await page.waitForLoadState('networkidle');

  // Load expected sequence from legacy verification
  const expectedSequence = require('../fixtures/legacy-sequences/login-sequence.json');

  // Compare sequences
  const comparison = compareAPISequences(apiCalls, expectedSequence);

  // Report results
  expect(comparison.matches).toBe(true);
  if (!comparison.matches) {
    console.log('Differences:', comparison.differences);
  }
});
```

**What This Validates:**
- ✅ Same API endpoints called
- ✅ Same order of calls
- ✅ Similar timing between calls
- ✅ Request payloads match
- ✅ Responses handled correctly

---

### Phase 3: WebSocket Verification Tests

**What I'll Create:**
```
test/websocket-verification/
├── ws-connection.spec.ts
└── ws-messages.spec.ts
```

**How They Work:**

```typescript
test('jam-ui establishes correct WebSocket connections', async ({ page }) => {
  const wsConnections = [];

  page.on('websocket', ws => {
    wsConnections.push({
      url: ws.url(),
      timestamp: Date.now()
    });

    ws.on('framereceived', frame => {
      // Record messages
    });
  });

  // Perform session join
  await joinSession(page);

  // Verify connections
  expect(wsConnections).toHaveLength(2);
  expect(wsConnections[0].url).toContain('localhost:3060');
  expect(wsConnections[1].url).toContain('jamkazam.local:6767');
});
```

---

### Phase 4: UI Component Tests

**What I'll Create:**
```
test/unit/
├── LoginForm.test.tsx
├── SessionCreationForm.test.tsx
└── SessionInterface.test.tsx
```

**Framework:** React Testing Library

**Example:**

```typescript
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import LoginForm from '../../src/components/auth/LoginForm';

test('LoginForm submits credentials correctly', async () => {
  const mockLogin = jest.fn();

  render(<LoginForm onLogin={mockLogin} />);

  fireEvent.change(screen.getByLabelText(/email/i), {
    target: { value: 'nuwan@jamkazam.com' }
  });
  fireEvent.change(screen.getByLabelText(/password/i), {
    target: { value: 'jam123' }
  });

  fireEvent.click(screen.getByRole('button', { name: /sign in/i }));

  await waitFor(() => {
    expect(mockLogin).toHaveBeenCalledWith({
      email: 'nuwan@jamkazam.com',
      password: 'jam123'
    });
  });
});
```

**What This Validates:**
- ✅ Forms render correctly
- ✅ User interactions work
- ✅ Validation functions properly
- ✅ Error messages display
- ✅ Loading states work

---

### Phase 5: E2E Integration Tests

**What I'll Create:**
```
test/e2e/
├── complete-session-flow.spec.ts
├── login-flow.spec.ts
└── session-creation-flow.spec.ts
```

**How They Work:**

```typescript
test('Complete session flow: login → create → join', async ({ page }) => {
  // Step 1: Login
  await page.goto('http://beta.jamkazam.local:4000/');
  await page.fill('[name="email"]', 'nuwan@jamkazam.com');
  await page.fill('[name="password"]', 'jam123');
  await page.click('button[type="submit"]');
  await expect(page).toHaveURL(/profile|dashboard/);

  // Step 2: Navigate to session creation
  await page.click('text=create session'); // Or appropriate selector
  await expect(page).toHaveURL(/session.*create/);

  // Step 3: Fill session form
  await page.fill('[name="session_name"]', 'Test Session');
  await page.selectOption('[name="session_type"]', 'private');
  await page.click('button[type="submit"]');

  // Step 4: Verify session interface loads
  await expect(page.locator('text=audio inputs')).toBeVisible();
  await expect(page.locator('text=personal mix')).toBeVisible();
  await expect(page.locator('text=LEAVE')).toBeVisible();

  // Take screenshot for verification
  await page.screenshot({ path: 'test-results/e2e-session-complete.png' });
});
```

---

### Phase 6: Comparison & Reporting

**What I'll Create:**
```
test/utils/sequence-comparator.ts
```

**Features:**
- Compare API call sequences
- Generate visual diff reports
- Highlight missing/extra calls
- Show timing differences
- Export to HTML/JSON

**Example Report:**
```
API Sequence Comparison Report
================================

Login Flow:
  ✅ POST /api/sessions - MATCH
  ✅ GET /api/users/{id} - MATCH
  ❌ GET /api/shopping_carts - MISSING in jam-ui
  ⚠️  GET /api/genres - Called later than expected (delay: 200ms)
  ✅ GET /api/countries - MATCH

Session Creation Flow:
  ✅ POST /api/sessions - MATCH
  ❌ POST /api/sessions/{id}/participants - MISSING
  ✅ GET /api/sessions/{id} - MATCH

Summary:
  Total API calls: 68/70 (2 missing)
  Sequence match: 85%
  Timing variance: ±150ms average
```

---

## 🔧 Technical Implementation Details

### Test Execution Flow

```
1. Load legacy baseline sequences from fixtures
2. Start jam-ui application at beta.jamkazam.local:4000
3. Execute test scenario (login, create session, join)
4. Capture all API calls and WebSocket messages
5. Compare with legacy baseline
6. Generate comparison report
7. Assert conformance criteria
```

### Key Utilities

**1. API Interceptor** (`test/utils/api-interceptor.ts`)
```typescript
export class APIInterceptor {
  private calls: APICall[] = [];

  intercept(page: Page) {
    page.on('request', req => this.recordRequest(req));
    page.on('response', res => this.recordResponse(res));
  }

  getCalls(): APICall[] {
    return this.calls;
  }

  compareWith(expected: APICall[]): ComparisonResult {
    // Comparison logic
  }
}
```

**2. WebSocket Monitor** (`test/utils/websocket-monitor.ts`)
```typescript
export class WebSocketMonitor {
  private connections: WSConnection[] = [];

  monitor(page: Page) {
    page.on('websocket', ws => {
      this.recordConnection(ws);
      ws.on('framereceived', frame => this.recordMessage(frame));
      ws.on('framesent', frame => this.recordMessage(frame));
    });
  }

  getConnections(): WSConnection[] {
    return this.connections;
  }
}
```

**3. Sequence Comparator** (`test/utils/sequence-comparator.ts`)
```typescript
export function compareAPISequences(
  actual: APICall[],
  expected: APICall[]
): ComparisonResult {
  return {
    matches: checkOrderAndContent(actual, expected),
    missing: findMissingCalls(actual, expected),
    extra: findExtraCalls(actual, expected),
    outOfOrder: findOutOfOrderCalls(actual, expected),
    timingVariance: calculateTimingVariance(actual, expected),
    report: generateHTMLReport(actual, expected)
  };
}
```

---

## 📦 Deliverables

### 1. Test Files
- ✅ 15-20 test specification files
- ✅ Test utilities and helpers
- ✅ Fixtures with legacy baseline data

### 2. Reports
- ✅ HTML comparison reports
- ✅ JSON data exports
- ✅ Screenshots at each step
- ✅ HAR files for network traffic

### 3. Documentation
- ✅ Test execution guide
- ✅ Failure analysis
- ✅ Recommendations for fixes

---

## ⏱️ Execution Timeline

**Immediate (Now):**
1. Create test infrastructure
2. Set up API interceptors
3. Create fixtures from verification data

**Phase 1 (30 mins):**
- API verification tests for login

**Phase 2 (1 hour):**
- API verification tests for session creation/join
- WebSocket tests

**Phase 3 (1 hour):**
- UI component tests

**Phase 4 (1 hour):**
- E2E tests

**Phase 5 (30 mins):**
- Generate reports
- Document findings

**Total Estimated Time:** 4 hours

---

## 📊 Success Metrics

### API Conformance
- **Target:** 95%+ API calls match
- **Threshold:** Missing < 5% of calls
- **Timing:** Within ±500ms variance

### WebSocket Conformance
- **Target:** Both connections established
- **Threshold:** Message count within 10% of legacy

### UI Functionality
- **Target:** 100% tests passing
- **Threshold:** No critical failures

### E2E Flow
- **Target:** Complete flow succeeds
- **Threshold:** All assertions pass

---

## 🚀 Getting Started

Once you approve this approach, I will:

1. ✅ Create all test infrastructure files
2. ✅ Implement API verification tests
3. ✅ Implement UI unit tests
4. ✅ Implement E2E tests
5. ✅ Run all tests against jam-ui
6. ✅ Generate comparison reports
7. ✅ Provide detailed findings and recommendations

**Ready to proceed?** I can start implementing immediately.

---

**Document Status:** Awaiting Approval
**Estimated Implementation Time:** 4 hours
**Expected Outcome:** Comprehensive test suite comparing jam-ui with legacy app
