# Testing Quick Start Guide

Quick reference for running tests in the Adopt-a-Street application.

## TL;DR - Run Tests Now

```bash
# Backend tests
cd backend && bun test

# Frontend tests
cd frontend && bun test

# Backend with coverage
cd backend && bun run test:coverage

# Frontend with coverage
cd frontend && bun run test:coverage
```

## What's Been Tested

### Backend (54.75% coverage, 109 passing tests)
✅ Authentication (register, login, get user)
✅ Streets (CRUD, adoption)
✅ Tasks (create, complete, update)
✅ Posts (create, like, comment)
✅ Events (create, RSVP)
✅ Rewards (list, redeem)
✅ Reports (create, resolve)
✅ User document model (validation, relationships)
✅ Street document model (GeoJSON, geospatial)
✅ Task document model (status, assignment)
✅ Post document model (likes, comments)
✅ Auth middleware (JWT validation)

### Frontend (Infrastructure ready)
✅ Login component (form, validation, submission)
✅ Register component (form, validation, password matching)
✅ ErrorBoundary (error catching, fallback UI)
✅ Auth flow integration (login → register → logout)
✅ MSW API mocking (all endpoints)

## Common Commands

### Backend

```bash
cd backend

# Watch mode (TDD)
bun run test:watch

# Single test file
bun test -- auth.test.js

# Tests matching pattern
bun test -- --testNamePattern="login"

# Coverage report
bun run test:coverage

# Verbose output
bun run test:verbose

# Update snapshots
bun test -- -u
```

### Frontend

```bash
cd frontend

# Watch mode (default)
bun test

# Coverage report
bun run test:coverage

# Single test file
bun test -- Login.test.js

# Tests matching pattern
bun test -- --testNamePattern="should render"

# No watch mode
CI=true bun test

# Update snapshots
bun test -- -u
```

## Writing Your First Test

### Backend Route Test

```javascript
const request = require('supertest');
const express = require('express');
const yourRoute = require('../../routes/your-route');
const { createTestUser } = require('../utils/testHelpers');

const app = express();
app.use(express.json());
app.use('/api/your-route', yourRoute);

describe('Your Route', () => {
  it('should work', async () => {
    const { token } = await createTestUser();

    const response = await request(app)
      .get('/api/your-route')
      .set('x-auth-token', token)
      .expect(200);

    expect(response.body).toHaveProperty('data');
  });
});
```

### Frontend Component Test

```javascript
import { render, screen, fireEvent } from '@testing-library/react';
import YourComponent from '../YourComponent';

describe('YourComponent', () => {
  it('should render', () => {
    render(<YourComponent />);

    const button = screen.getByRole('button');
    fireEvent.click(button);

    expect(screen.getByText(/success/i)).toBeInTheDocument();
  });
});
```

## Test Helpers Available

### Backend

```javascript
const {
  createTestUser,       // Returns { user, token }
  createTestUsers,      // Creates multiple users
  createTestStreet,     // Creates street with location
  createTestTask,       // Creates task
  createTestPost,       // Creates post
  createTestEvent,      // Creates event
  createTestReward,     // Creates reward
  createTestReport,     // Creates report
} = require('../utils/testHelpers');
```

### Frontend

MSW handlers automatically mock all API endpoints:
- `/api/auth/*` - Authentication
- `/api/streets/*` - Streets
- `/api/tasks/*` - Tasks
- `/api/posts/*` - Posts
- `/api/events/*` - Events
- `/api/rewards/*` - Rewards
- `/api/users/*` - Users

## Coverage Reports

After running tests with coverage, open the HTML report:

```bash
# Backend
cd backend && bun run test:coverage
open coverage/lcov-report/index.html

# Frontend
cd frontend && bun run test:coverage
open coverage/lcov-report/index.html
```

## Current Coverage Status

### Backend
- Overall: 54.75%
- Auth middleware: 100% ✅
- Models: 82.50% ✅
- Routes: 45.84% ⚠️

### Frontend
- Infrastructure: Ready ✅
- Components tested: 3/11
- Integration tests: 1 suite

## Test Structure

```
backend/
├── __tests__/
│   ├── setup.js              # Test setup
│   ├── routes/               # API route tests
│   ├── models/               # Model tests
│   ├── middleware/           # Middleware tests
│   └── utils/
│       └── testHelpers.js    # Test utilities
└── jest.config.js

frontend/src/
├── setupTests.js             # Test setup
├── mocks/
│   ├── handlers.js           # API mocks
│   └── server.js             # MSW server
├── __tests__/                # Integration tests
└── components/
    └── __tests__/            # Component tests
```

## Troubleshooting

### Backend

**Tests timeout**
```bash
# Increase timeout in jest.config.js
testTimeout: 30000
```

**CouchDB connection issues**
```bash
# Check CouchDB testing utilities are installed
bun list @couchdb/test-helpers
```

### Frontend

**MSW not intercepting**
```javascript
// Check setupTests.js has:
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
```

**React Router errors**
```javascript
// Wrap component with BrowserRouter
import { BrowserRouter } from 'react-router-dom';

render(
  <BrowserRouter>
    <YourComponent />
  </BrowserRouter>
);
```

**Auth context errors**
```javascript
// Provide AuthContext
import { AuthContext } from '../../context/AuthContext';

const mockContext = {
  auth: { isAuthenticated: false, loading: false },
  login: jest.fn(),
};

render(
  <AuthContext.Provider value={mockContext}>
    <YourComponent />
  </AuthContext.Provider>
);
```

## Next Steps

1. **Read the full docs**: [TESTING.md](TESTING.md)
2. **Check the summary**: [TEST_IMPLEMENTATION_SUMMARY.md](TEST_IMPLEMENTATION_SUMMARY.md)
3. **Run the tests**: Follow commands above
4. **Write your tests**: Use templates provided

## Questions?

- See [TESTING.md](TESTING.md) for comprehensive documentation
- Check existing tests in `__tests__/` for examples
- Review test helpers in `testHelpers.js`

---

**Happy Testing!** 🧪✅
