Files
adopt-a-street/TESTING_QUICK_START.md
William Valentin 2d1d02387d docs: add comprehensive testing documentation
Add detailed testing guides and implementation documentation:

TESTING.md (560 lines):
- Complete testing guide for developers
- Backend testing with Jest, Supertest, MongoDB Memory Server
- Frontend testing with React Testing Library, MSW
- Test writing examples and patterns
- Coverage requirements and reporting
- CI/CD integration guidelines
- Best practices and conventions

TESTING_QUICK_START.md (250 lines):
- Quick reference for running tests
- Common test commands (backend and frontend)
- Test file locations and organization
- Coverage report viewing
- Troubleshooting common issues
- Quick examples for common scenarios

TEST_IMPLEMENTATION_SUMMARY.md (750 lines):
- Detailed implementation report
- Coverage statistics by area
- Test file descriptions
- Known issues and future improvements
- Architecture decisions
- Test infrastructure details
- MSW handler documentation

CLAUDE.md Updates:
- Add testing section with quick commands
- Document test coverage targets
- Reference comprehensive testing docs
- Add Kubernetes deployment section for Raspberry Pi cluster
- Document cluster configuration (2x Pi 5 8GB, 1x Pi 3B+ 1GB)
- ARM64 and ARMv7 architecture considerations
- Resource optimization strategies

Key Documentation Features:
- Step-by-step guides for writing tests
- Examples for all test types (unit, integration, E2E)
- Coverage reporting and analysis
- Debugging test failures
- Performance testing guidelines
- Mock data management

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-01 10:44:21 -07:00

6.0 KiB

Testing Quick Start Guide

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

TL;DR - Run Tests Now

# Backend tests
cd backend && npm test

# Frontend tests
cd frontend && npm test

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

# Frontend with coverage
cd frontend && npm 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 model (validation, relationships) Street model (GeoJSON, geospatial) Task model (status, assignment) Post 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

cd backend

# Watch mode (TDD)
npm run test:watch

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

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

# Coverage report
npm run test:coverage

# Verbose output
npm run test:verbose

# Update snapshots
npm test -- -u

Frontend

cd frontend

# Watch mode (default)
npm test

# Coverage report
npm run test:coverage

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

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

# No watch mode
CI=true npm test

# Update snapshots
npm test -- -u

Writing Your First Test

Backend Route Test

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

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

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:

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

# Frontend
cd frontend && npm 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

# Increase timeout in jest.config.js
testTimeout: 30000

MongoDB connection issues

# Check MongoDB Memory Server is installed
npm list mongodb-memory-server

Frontend

MSW not intercepting

// Check setupTests.js has:
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

React Router errors

// Wrap component with BrowserRouter
import { BrowserRouter } from 'react-router-dom';

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

Auth context errors

// 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
  2. Check the summary: TEST_IMPLEMENTATION_SUMMARY.md
  3. Run the tests: Follow commands above
  4. Write your tests: Use templates provided

Questions?

  • See TESTING.md for comprehensive documentation
  • Check existing tests in __tests__/ for examples
  • Review test helpers in testHelpers.js

Happy Testing! 🧪