# VIP Coordinator - Testing Guide
This guide covers the complete testing infrastructure for the VIP Coordinator application.
## Overview
The testing setup includes:
- **Backend Tests**: Jest with Supertest for API testing
- **Frontend Tests**: Vitest with React Testing Library
- **E2E Tests**: Playwright for end-to-end testing
- **Test Database**: Separate PostgreSQL instance for tests
- **CI/CD Pipeline**: GitHub Actions for automated testing
## Quick Start
### Running All Tests
```bash
# Using Make
make test
# Using Docker Compose
docker-compose -f docker-compose.test.yml up
```
### Running Specific Test Suites
```bash
# Backend tests only
make test-backend
# Frontend tests only
make test-frontend
# E2E tests only
make test-e2e
# Generate coverage reports
make test-coverage
```
## Backend Testing
### Setup
The backend uses Jest with TypeScript support and Supertest for API testing.
**Configuration**: `backend/jest.config.js`
**Test Setup**: `backend/src/tests/setup.ts`
### Writing Tests
#### Unit Tests
```typescript
// backend/src/services/__tests__/authService.test.ts
import { testPool } from '../../tests/setup';
import { testUsers, insertTestUser } from '../../tests/fixtures';
describe('AuthService', () => {
it('should create a new user', async () => {
// Your test here
});
});
```
#### Integration Tests
```typescript
// backend/src/routes/__tests__/vips.test.ts
import request from 'supertest';
import app from '../../app';
describe('VIP API', () => {
it('GET /api/vips should return all VIPs', async () => {
const response = await request(app)
.get('/api/vips')
.set('Authorization', 'Bearer token');
expect(response.status).toBe(200);
});
});
```
### Test Utilities
- **Fixtures**: `backend/src/tests/fixtures.ts` - Pre-defined test data
- **Test Database**: Automatically set up and torn down for each test
- **Mock Services**: JWT, Google OAuth, etc.
### Running Backend Tests
```bash
cd backend
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # With coverage
```
## Frontend Testing
### Setup
The frontend uses Vitest with React Testing Library.
**Configuration**: `frontend/vitest.config.ts`
**Test Setup**: `frontend/src/tests/setup.ts`
### Writing Tests
#### Component Tests
```typescript
// frontend/src/components/__tests__/VipForm.test.tsx
import { render, screen } from '../../tests/test-utils';
import VipForm from '../VipForm';
describe('VipForm', () => {
it('renders all form fields', () => {
render();
expect(screen.getByLabelText(/full name/i)).toBeInTheDocument();
});
});
```
#### Page Tests
```typescript
// frontend/src/pages/__tests__/Dashboard.test.tsx
import { render, waitFor } from '../../tests/test-utils';
import Dashboard from '../Dashboard';
describe('Dashboard', () => {
it('loads and displays VIPs', async () => {
render();
await waitFor(() => {
expect(screen.getByText('John Doe')).toBeInTheDocument();
});
});
});
```
### Test Utilities
- **Custom Render**: Includes providers (Router, Toast, etc.)
- **Mock Data**: Pre-defined users, VIPs, drivers
- **API Mocks**: Mock fetch responses
### Running Frontend Tests
```bash
cd frontend
npm test # Run all tests
npm run test:ui # With UI
npm run test:coverage # With coverage
```
## E2E Testing
### Setup
E2E tests use Playwright for cross-browser testing.
**Configuration**: `e2e/playwright.config.ts`
### Writing E2E Tests
```typescript
// e2e/tests/vip-management.spec.ts
import { test, expect } from '@playwright/test';
test('create new VIP', async ({ page }) => {
await page.goto('/');
// Login flow
await page.click('text=Add VIP');
await page.fill('[name="name"]', 'Test VIP');
await page.click('text=Submit');
await expect(page.locator('text=Test VIP')).toBeVisible();
});
```
### Running E2E Tests
```bash
# Local development
npx playwright test
# In Docker
make test-e2e
```
## Database Testing
### Test Database Setup
- Separate database instance for tests
- Automatic schema creation and migrations
- Test data seeding
- Cleanup after each test
### Database Commands
```bash
# Set up test database with schema and seed data
make db-setup
# Run migrations only
make db-migrate
# Seed test data
make db-seed
```
### Creating Migrations
```bash
cd backend
npm run db:migrate:create "add_new_column"
```
## Docker Test Environment
### Configuration
**File**: `docker-compose.test.yml`
Services:
- `test-db`: PostgreSQL for tests (port 5433)
- `test-redis`: Redis for tests (port 6380)
- `backend-test`: Backend test runner
- `frontend-test`: Frontend test runner
- `e2e-test`: E2E test runner
### Environment Variables
Create `.env.test` based on `.env.example`:
```env
DATABASE_URL=postgresql://test_user:test_password@test-db:5432/vip_coordinator_test
REDIS_URL=redis://test-redis:6379
GOOGLE_CLIENT_ID=test_client_id
# ... other test values
```
## CI/CD Pipeline
### GitHub Actions Workflows
#### Main CI Pipeline
**File**: `.github/workflows/ci.yml`
Runs on every push and PR:
1. Backend tests with coverage
2. Frontend tests with coverage
3. Security scanning
4. Docker image building
5. Deployment (staging/production)
#### E2E Test Schedule
**File**: `.github/workflows/e2e-tests.yml`
Runs daily or on-demand:
- Cross-browser testing
- Multiple environments
- Result notifications
#### Dependency Updates
**File**: `.github/workflows/dependency-update.yml`
Weekly automated updates:
- npm package updates
- Security fixes
- Automated PR creation
## Best Practices
### Test Organization
- Group related tests in describe blocks
- Use descriptive test names
- One assertion per test when possible
- Use beforeEach/afterEach for setup/cleanup
### Test Data
- Use fixtures for consistent test data
- Clean up after tests
- Don't rely on test execution order
- Use unique identifiers to avoid conflicts
### Mocking
- Mock external services (Google OAuth, APIs)
- Use test doubles for database operations
- Mock time-dependent operations
### Performance
- Run tests in parallel when possible
- Use test database in memory (tmpfs)
- Cache Docker layers in CI
## Troubleshooting
### Common Issues
#### Port Conflicts
```bash
# Check if ports are in use
lsof -i :5433 # Test database
lsof -i :6380 # Test Redis
```
#### Database Connection Issues
```bash
# Ensure test database is running
docker-compose -f docker-compose.test.yml up test-db -d
# Check logs
docker-compose -f docker-compose.test.yml logs test-db
```
#### Test Timeouts
- Increase timeout in test configuration
- Check for proper async/await usage
- Ensure services are ready before tests
### Debug Mode
```bash
# Run tests with debug output
DEBUG=* npm test
# Run specific test file
npm test -- authService.test.ts
# Run tests matching pattern
npm test -- --grep "should create user"
```
## Coverage Reports
Coverage reports are generated in:
- Backend: `backend/coverage/`
- Frontend: `frontend/coverage/`
View HTML reports:
```bash
# Backend
open backend/coverage/lcov-report/index.html
# Frontend
open frontend/coverage/index.html
```
## Contributing
When adding new features:
1. Write tests first (TDD approach)
2. Ensure all tests pass
3. Maintain >80% code coverage
4. Update test documentation
## Resources
- [Jest Documentation](https://jestjs.io/docs/getting-started)
- [Vitest Documentation](https://vitest.dev/guide/)
- [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/)
- [Playwright Documentation](https://playwright.dev/docs/intro)
- [Supertest Documentation](https://github.com/visionmedia/supertest)