Files
adopt-a-street/TESTING_QUICK_START.md
William Valentin 37b22039a7 docs: update npm commands to bun in README and documentation files
- Replace npm install with bun install
- Replace npm start/test/build with bun equivalents
- Update deployment and testing documentation
- Maintain consistency with project's bun-first approach

🤖 Generated with [AI Assistant]

Co-Authored-By: AI Assistant <noreply@ai-assistant.com>
2025-11-01 12:41:59 -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 && 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 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)
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

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

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 && 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

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

MongoDB connection issues

# Check MongoDB Memory Server is installed
bun 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! 🧪