# Contact Form E2E Test Suite

Comprehensive end-to-end test suite for the contact form, covering form functionality, database integration, API endpoints, bilingual support, and accessibility.

## Test Coverage

### 1. Form Functionality (English)
- ✅ Contact page loads correctly
- ✅ All required form fields are present
- ✅ Required field validation
- ✅ Email format validation
- ✅ Message length validation (min 10 characters)
- ✅ Character counter display
- ✅ Consent checkbox requirement
- ✅ Successful form submission

### 2. Database Integration (Supabase)
- ✅ Submissions saved to `contact_submissions` table
- ✅ All form fields stored correctly
- ✅ Metadata captured (IP, user agent, language)
- ✅ Timestamps automatically set
- ✅ Preferred language stored
- ✅ Consent flag recorded

### 3. File Upload Functionality
- ✅ File upload area displayed
- ✅ Valid file types accepted (JPEG, PNG, GIF, WebP, PDF)
- ✅ Multiple file upload support
- ✅ File size limit enforced (10MB)
- ✅ Maximum file count (3 files)

### 4. API Endpoint Testing
- ✅ POST `/api/contact/submit` accepts valid data
- ✅ Returns 400 for invalid data
- ✅ Rate limiting enforced (3 submissions per 5 minutes)
- ✅ CORS headers present
- ✅ GET requests rejected with 405
- ✅ OPTIONS requests handled (CORS preflight)

### 5. Bilingual Support (Arabic)
- ✅ Arabic page loads correctly
- ✅ RTL layout for Arabic
- ✅ Arabic form submission works
- ✅ Language preference stored in database

### 6. Accessibility
- ✅ All form fields have labels
- ✅ Keyboard navigation support
- ✅ Proper heading hierarchy (single h1)
- ✅ Submit button has accessible name
- ✅ Form errors announced to screen readers

### 7. Error Handling
- ✅ Server errors displayed gracefully
- ✅ Network errors handled
- ✅ Errors cleared on user input

### 8. Responsive Design
- ✅ Mobile viewport (375x667)
- ✅ Tablet viewport (768x1024)
- ✅ Desktop viewport (1920x1080)

### 9. Form State Management
- ✅ Form disabled during submission
- ✅ Loading indicator shown
- ✅ Form reset after success

### 10. Performance
- ✅ Page loads within 5 seconds
- ✅ No console errors on load

## Running the Tests

### Prerequisites

1. **Application running on port 9000**:
   ```bash
   cd mawidi-site
   npm run dev
   ```

2. **Supabase running** (local or production):
   - Local: `supabase start`
   - Production: Set `NEXT_PUBLIC_SUPABASE_URL` in `.env.local`

3. **Environment variables configured**:
   ```bash
   # Required for database tests
   NEXT_PUBLIC_SUPABASE_URL=http://127.0.0.1:54321
   NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
   SUPABASE_SERVICE_ROLE_KEY=your-service-key

   # Required for rate limiting tests
   UPSTASH_REDIS_REST_URL=your-redis-url
   UPSTASH_REDIS_REST_TOKEN=your-redis-token
   ```

### Run All Tests

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

# Run with UI (interactive mode)
npm run test:e2e:ui -- contact-form.spec.ts

# Run in headed mode (see browser)
npm run test:e2e:headed -- contact-form.spec.ts

# Debug specific test
npm run test:e2e:debug -- contact-form.spec.ts
```

### Run Specific Test Suites

```bash
# Test only form functionality
npm run test:e2e -- contact-form.spec.ts -g "Form Functionality"

# Test only database integration
npm run test:e2e -- contact-form.spec.ts -g "Database Integration"

# Test only API endpoints
npm run test:e2e -- contact-form.spec.ts -g "API Endpoint Testing"

# Test only Arabic/bilingual
npm run test:e2e -- contact-form.spec.ts -g "Bilingual Support"

# Test only accessibility
npm run test:e2e -- contact-form.spec.ts -g "Accessibility"
```

### Run Specific Browser

```bash
# Chromium only
npm run test:e2e -- contact-form.spec.ts --project=chromium

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

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

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

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

## Test Data Cleanup

The test suite automatically cleans up test data from Supabase after each test:

- **Automatic cleanup**: All test submissions are deleted using `testEmails` array
- **Safety net**: Additional cleanup removes any emails containing "test"
- **File cleanup**: Uploaded files are also removed from Supabase Storage

### Manual Cleanup

If tests are interrupted, you can manually clean up test data:

```sql
-- Connect to Supabase and run:
DELETE FROM contact_submissions
WHERE email LIKE '%test%@%'
OR email LIKE '%ratelimit%@%';
```

## Understanding Test Results

### Successful Test Run

```
✓ Form Functionality - English (8 tests)
✓ Database Integration (3 tests)
✓ File Upload Functionality (4 tests)
✓ API Endpoint Testing (7 tests)
✓ Bilingual Support - Arabic (4 tests)
✓ Accessibility (5 tests)
✓ Error Handling (3 tests)
✓ Responsive Design (3 tests)
✓ Form State Management (3 tests)
✓ Performance (2 tests)

42 passed (1m 30s)
```

### Skipped Tests

Some tests may be skipped if Supabase is not available:

```
⊘ Database Integration > should save submission to Supabase database
  Supabase connection not available - test skipped
```

This is expected in environments without Supabase configured.

### Failed Tests

If tests fail, check:

1. **Application running**: `http://localhost:9000` should be accessible
2. **Supabase configured**: Check environment variables
3. **Rate limiting**: Previous tests may have triggered rate limits (wait 5 minutes)
4. **Network issues**: Ensure stable internet connection for API calls

## Test Configuration

### Playwright Configuration

Tests use the project's Playwright configuration (`playwright.config.ts`):

- **Base URL**: `http://localhost:9000`
- **Retries**: 2 in CI, 0 locally
- **Timeout**: Default 30 seconds per test
- **Screenshots**: On failure only
- **Videos**: Retained on failure
- **Trace**: On first retry

### Custom Timeouts

Some operations have custom timeouts:

```typescript
// Form submission (10 seconds)
await expect(successMessage).toBeVisible({ timeout: 10000 });

// Database wait with retries (5 seconds)
const submission = await SupabaseTestHelpers.waitForSubmission(email, 10, 500);
```

## Test Helpers

### TestHelpers (test-utils.ts)

General test utilities:

- `navigateToPage(path, lang)` - Navigate with language prefix
- `fillForm(formData)` - Fill form fields
- `checkAccessibility()` - Run accessibility checks
- `testResponsive()` - Test multiple viewports
- `generateTestData()` - Generate unique test data

### SupabaseTestHelpers (supabase-test-utils.ts)

Database testing utilities:

- `cleanupTestSubmissions(emails)` - Delete test data
- `getSubmissionByEmail(email)` - Retrieve submission
- `waitForSubmission(email)` - Wait for DB write with retries
- `verifySubmissionData(submission, expected)` - Validate data
- `verifyAttachments(submission, count)` - Check file uploads
- `checkConnection()` - Test Supabase availability

## Continuous Integration

### GitHub Actions

Tests run automatically on:

- Push to main/develop branches
- Pull requests
- Manual workflow dispatch

Example CI configuration:

```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 }}
    SUPABASE_SERVICE_ROLE_KEY: ${{ secrets.SUPABASE_SERVICE_KEY }}
```

### Test Reports

After running tests, view detailed reports:

```bash
# Open HTML report
npm run test:e2e:report

# Reports are saved to:
# - playwright-report/index.html (HTML)
# - test-results/results.json (JSON)
# - test-results/junit.xml (JUnit)
```

## Troubleshooting

### Common Issues

**1. Tests fail with "Navigation timeout"**
- Check application is running on port 9000
- Increase timeout in `playwright.config.ts`

**2. Database tests are skipped**
- Verify Supabase environment variables
- Check Supabase is running (`supabase status`)
- Test connection manually

**3. Rate limiting tests fail**
- Wait 5 minutes for rate limit to reset
- Check Redis/Upstash is configured
- Verify IP address detection works

**4. File upload tests incomplete**
- Tests verify UI only (no actual file upload)
- To test file uploads, create test files in `tests/fixtures/`

**5. Arabic tests fail**
- Check translations are complete in `lib/config/translations/ar.ts`
- Verify RTL styling is applied

### Debug Mode

Run tests in debug mode for detailed output:

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

# Verbose logging
DEBUG=pw:api npm run test:e2e -- contact-form.spec.ts

# Show browser console
npm run test:e2e:headed -- contact-form.spec.ts
```

### Test Isolation

Each test is isolated:

- Fresh browser context
- Clean database state (via cleanup)
- Independent test data (via `generateTestData()`)
- No shared state between tests

## Best Practices

1. **Always use `generateTestData()`** for unique test emails
2. **Add emails to `testEmails` array** for automatic cleanup
3. **Wait for Supabase with retries** using `waitForSubmission()`
4. **Check Supabase connection** before database tests
5. **Use appropriate timeouts** for async operations
6. **Clean up resources** in `afterEach` hooks
7. **Test both success and failure** paths
8. **Verify database state** after form submissions

## Future Enhancements

Potential test improvements:

- [ ] Actual file upload testing with test fixtures
- [ ] Screenshot comparison for visual regression
- [ ] Performance metrics collection
- [ ] Email notification verification
- [ ] reCAPTCHA integration testing (when enabled)
- [ ] Multi-language form validation messages
- [ ] Attachment preview functionality
- [ ] Form auto-save/recovery testing
- [ ] Cross-browser compatibility matrix

## Contributing

When adding new tests:

1. Follow existing test structure and naming
2. Add tests to appropriate describe block
3. Include both positive and negative test cases
4. Document any new test helpers
5. Ensure cleanup is implemented
6. Update this README with new coverage

## License

Part of the Mawidi project. See main project LICENSE file.
