# Contact Form Tests - Quick Reference

## Quick Start

```bash
# 1. Start the application
npm run dev

# 2. Start Supabase (if testing database)
supabase start

# 3. Run all tests
npm run test:e2e -- contact-form.spec.ts
```

## Common Commands

### Run All Tests
```bash
npm run test:e2e -- contact-form.spec.ts
```

### Run Specific Test Suite
```bash
# Using grep pattern
npm run test:e2e -- contact-form.spec.ts -g "Form Functionality"
npm run test:e2e -- contact-form.spec.ts -g "Database Integration"
npm run test:e2e -- contact-form.spec.ts -g "API Endpoint"
npm run test:e2e -- contact-form.spec.ts -g "Bilingual"
npm run test:e2e -- contact-form.spec.ts -g "Accessibility"

# Using test runner script
./tests/run-contact-tests.sh --suite form
./tests/run-contact-tests.sh --suite database
./tests/run-contact-tests.sh --suite api
./tests/run-contact-tests.sh --suite arabic
./tests/run-contact-tests.sh --suite accessibility
```

### Debug Tests
```bash
# Playwright Inspector
npm run test:e2e:debug -- contact-form.spec.ts

# With browser visible
npm run test:e2e:headed -- contact-form.spec.ts

# Interactive UI mode
npm run test:e2e:ui -- contact-form.spec.ts

# Specific test in debug mode
./tests/run-contact-tests.sh --suite form --debug
```

### Run Specific Browser
```bash
# Chromium (default)
npm run test:e2e -- contact-form.spec.ts --project=chromium

# Firefox
npm run test:e2e -- contact-form.spec.ts --project=firefox

# WebKit (Safari)
npm run test:e2e -- contact-form.spec.ts --project=webkit

# Mobile browsers
npm run test:e2e -- contact-form.spec.ts --project="Mobile Chrome"
npm run test:e2e -- contact-form.spec.ts --project="Mobile Safari"

# Using test runner
./tests/run-contact-tests.sh --browser firefox
./tests/run-contact-tests.sh --browser webkit
./tests/run-contact-tests.sh --browser mobile-chrome
```

### View Test Reports
```bash
# Open HTML report
npm run test:e2e:report

# Report locations:
# - playwright-report/index.html (interactive HTML)
# - test-results/results.json (machine-readable)
# - test-results/junit.xml (CI integration)
```

## Test Suite Overview

| Suite | Tests | What It Tests |
|-------|-------|---------------|
| **Form Functionality** | 8 | Field validation, submission, character counting |
| **Database Integration** | 3 | Supabase storage, metadata capture, data integrity |
| **File Upload** | 4 | File types, size limits, multiple uploads |
| **API Endpoint** | 7 | Request validation, rate limiting, CORS |
| **Bilingual Support** | 4 | Arabic page, RTL layout, language storage |
| **Accessibility** | 5 | Labels, keyboard navigation, screen readers |
| **Error Handling** | 3 | Server errors, network failures, error clearing |
| **Responsive Design** | 3 | Mobile, tablet, desktop viewports |
| **State Management** | 3 | Loading states, form reset, button states |
| **Performance** | 2 | Load time, console errors |

**Total: 42 tests**

## Environment Setup

### Required Environment Variables
```bash
# Supabase (required for database tests)
NEXT_PUBLIC_SUPABASE_URL=http://127.0.0.1:54321
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key-here
SUPABASE_SERVICE_ROLE_KEY=your-service-key-here

# Rate Limiting (required for rate limit tests)
UPSTASH_REDIS_REST_URL=your-redis-url
UPSTASH_REDIS_REST_TOKEN=your-redis-token

# reCAPTCHA (currently disabled for testing)
NEXT_PUBLIC_RECAPTCHA_SITE_KEY=your-site-key
RECAPTCHA_SECRET_KEY=your-secret-key
```

### Local Supabase Setup
```bash
# Install Supabase CLI
npm install -g supabase

# Start local Supabase
supabase start

# Get connection details
supabase status

# Stop when done
supabase stop
```

## Test Data Cleanup

### Automatic Cleanup
Tests automatically clean up after themselves:
- All test submissions deleted from database
- Test files removed from storage
- Rate limit counters reset (after 5 minutes)

### Manual Cleanup
```sql
-- If tests are interrupted, run in Supabase:
DELETE FROM contact_submissions
WHERE email LIKE '%test%@%';
```

## Troubleshooting

### Application Not Running
```bash
# Error: Navigation timeout
# Solution: Start the app
npm run dev

# Verify it's running
curl http://localhost:9000
```

### Supabase Not Available
```bash
# Error: Database tests skipped
# Solution: Start Supabase
supabase start

# Check status
supabase status
```

### Rate Limit Reached
```bash
# Error: 429 Too Many Requests
# Solution: Wait 5 minutes or reset Redis

# If using local Redis:
docker exec -it mawidi-redis redis-cli
FLUSHDB
```

### Tests Hanging
```bash
# Kill stuck processes
pkill -f playwright

# Clear test cache
rm -rf test-results/
rm -rf playwright-report/

# Restart tests
npm run test:e2e -- contact-form.spec.ts
```

## CI/CD Integration

### GitHub Actions Example
```yaml
- name: Run Contact Form Tests
  run: npm run test:e2e -- contact-form.spec.ts
  env:
    NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
    NEXT_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.SUPABASE_ANON_KEY }}

- name: Upload Test Results
  if: always()
  uses: actions/upload-artifact@v3
  with:
    name: playwright-report
    path: playwright-report/
```

### Run Only Fast Tests in CI
```bash
# Skip database tests (faster)
npm run test:e2e -- contact-form.spec.ts --grep-invert "Database Integration"

# Run only critical tests
npm run test:e2e -- contact-form.spec.ts -g "Form Functionality|API Endpoint"
```

## Performance Tips

### Faster Test Runs
```bash
# Run in parallel (Chromium only)
npm run test:e2e -- contact-form.spec.ts --project=chromium --workers=4

# Skip slow tests
npm run test:e2e -- contact-form.spec.ts --grep-invert "Database|File Upload"

# Run headless (default, faster)
npm run test:e2e -- contact-form.spec.ts
```

### Slower but More Thorough
```bash
# Run all browsers
npm run test:e2e -- contact-form.spec.ts

# Run with retries
npm run test:e2e -- contact-form.spec.ts --retries=2

# Run headed for visual verification
npm run test:e2e:headed -- contact-form.spec.ts
```

## File Locations

```
tests/
├── contact-form.spec.ts          # Main test file (42 tests)
├── helpers/
│   ├── test-utils.ts             # General test utilities
│   └── supabase-test-utils.ts    # Database test helpers
├── run-contact-tests.sh          # Test runner script
├── CONTACT_FORM_TESTS.md         # Full documentation
└── QUICK_REFERENCE.md            # This file
```

## Test Helper Usage

### Generate Test Data
```typescript
import { generateTestData } from './helpers/test-utils';

const testData = generateTestData();
// Returns: { email: 'test123@example.com', name: 'Test User 123', ... }
```

### Database Verification
```typescript
import { SupabaseTestHelpers } from './helpers/supabase-test-utils';

// Wait for submission
const submission = await SupabaseTestHelpers.waitForSubmission(email);

// Verify data
const isValid = SupabaseTestHelpers.verifySubmissionData(submission, {
  name: 'Test User',
  email: 'test@example.com',
  topic: 'sales',
});
```

### Cleanup
```typescript
// In afterEach hook
await SupabaseTestHelpers.cleanupTestSubmissions(testEmails);
```

## Common Test Patterns

### Form Submission Test
```typescript
test('should submit form', async ({ page }) => {
  await page.goto('/en/contact');

  const testData = generateTestData();
  await page.locator('input[name="name"]').fill(testData.name);
  await page.locator('input[name="email"]').fill(testData.email);
  await page.locator('select[name="topic"]').selectOption('sales');
  await page.locator('textarea[name="message"]').fill('Test message');
  await page.locator('input[name="consent"]').check();

  await page.locator('button[type="submit"]').click();

  await expect(page.locator('text=/success/i')).toBeVisible();
});
```

### API Request Test
```typescript
test('API should accept valid request', async ({ request }) => {
  const formData = new FormData();
  formData.append('name', 'Test User');
  formData.append('email', 'test@example.com');
  // ... more fields

  const response = await request.post('/api/contact/submit', {
    data: formData,
  });

  expect(response.status()).toBe(200);
});
```

### Database Verification Test
```typescript
test('should save to database', async ({ page }) => {
  // Submit form...

  const submission = await SupabaseTestHelpers.waitForSubmission(email);
  expect(submission).not.toBeNull();
  expect(submission.name).toBe('Test User');
});
```

## Additional Resources

- Full documentation: `tests/CONTACT_FORM_TESTS.md`
- Playwright docs: https://playwright.dev
- Supabase docs: https://supabase.com/docs
- Project README: `../README.md`

## Support

For issues or questions:
1. Check full documentation in `CONTACT_FORM_TESTS.md`
2. Review test output and reports
3. Check application logs
4. Verify environment configuration
5. Review Supabase logs (if database tests fail)
