My App
Api

Testing Guide

Comprehensive testing guide for the HMS API

The HMS API uses a comprehensive testing strategy with unit tests, integration tests, and end-to-end (E2E) tests.

Test Structure

apps/api/
├── src/
│   ├── __tests__/
│   │   ├── unit/              # Unit tests
│   │   │   ├── password.test.ts
│   │   │   ├── jwt.test.ts
│   │   │   ├── client-auth.service.test.ts
│   │   │   ├── admin-auth.service.test.ts
│   │   │   └── auth.middleware.test.ts
│   │   └── integration/        # Integration tests
│   │       └── auth.test.ts
└── vitest.config.ts

e2e/                              # E2E tests (root level)
├── client-auth.spec.ts
├── admin-auth.spec.ts
└── hosting-order-flow.spec.ts    # Hosting order flow (landing → domain → checkout)

Running Tests

Unit and Integration Tests

# Run all tests
cd apps/api
pnpm test

# Run tests in watch mode
pnpm test

# Run tests with UI
pnpm test:ui

# Run tests with coverage
pnpm test:coverage

# Run tests once (CI mode)
pnpm test:run

E2E Tests

# Run E2E tests (from root)
pnpm test:e2e

# Run E2E tests with UI
pnpm test:e2e:ui

# Run E2E tests in headed mode
pnpm test:e2e:headed

Test Types

Unit Tests

Unit tests test individual functions and utilities in isolation.

Examples:

  • Password hashing and verification
  • JWT token generation and validation
  • Service methods (register, login, etc.)
  • Middleware functions

Location: apps/api/src/__tests__/unit/

Integration Tests

Integration tests test API endpoints with mocked dependencies.

Examples:

  • POST /register endpoint
  • POST /login endpoint
  • GET /profile endpoint
  • Error handling

Location: apps/api/src/__tests__/integration/

E2E Tests

E2E tests test complete user flows across the entire application.

Examples:

  • Client registration → login → profile access
  • Admin login → profile access
  • Password reset flow

Location: e2e/

Writing Tests

Unit Test Example

import { describe, it, expect } from 'vitest'
import { hashPassword, verifyPassword } from '../../lib/password'

describe('Password Utilities', () => {
  it('should hash a password', async () => {
    const password = 'testpassword123'
    const hash = await hashPassword(password)
    
    expect(hash).toBeDefined()
    expect(hash).not.toBe(password)
  })
})

Integration Test Example

import { describe, it, expect, vi } from 'vitest'
import { Hono } from 'hono'
import { clientAuthRoutes } from '../../features/auth/client-auth.routes'

const app = new Hono()
app.route('/client/auth', clientAuthRoutes)

describe('Client Auth Endpoints', () => {
  it('should register a new client', async () => {
    const req = new Request('http://localhost/client/auth/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: '[email protected]',
        password: 'password123',
        name: 'New Client',
      }),
    })

    const res = await app.request(req)
    const data = await res.json()

    expect(res.status).toBe(201)
    expect(data.email).toBe('[email protected]')
  })
})

E2E Test Example

import { test, expect } from '@playwright/test'

test('should complete registration flow', async ({ page }) => {
  await page.goto('http://localhost:3001/auth/register')
  
  await page.fill('input[name="name"]', 'Test Client')
  await page.fill('input[name="email"]', '[email protected]')
  await page.fill('input[name="password"]', 'TestPassword123!')
  
  await page.click('button[type="submit"]')
  
  await expect(page).toHaveURL(/.*\/$/)
})

Test Coverage

Current Coverage

  • ✅ Password utilities
  • ✅ JWT utilities
  • ✅ Authentication services (client and admin)
  • ✅ Authentication middleware
  • ✅ API endpoints (integration)
  • ✅ E2E flows (client and admin)

Coverage Goals

  • Aim for >80% code coverage
  • Focus on critical paths (authentication, authorization)
  • Test error cases and edge cases

Mocking

Prisma Mocking

vi.mock('../../lib/db', () => ({
  default: {
    client: {
      findUnique: vi.fn(),
      create: vi.fn(),
    },
  },
}))

Email Service Mocking

vi.mock('../../lib/email', () => ({
  emailService: {
    sendPasswordResetEmail: vi.fn().mockResolvedValue(undefined),
  },
}))

CI/CD Integration

GitHub Actions Example

name: Tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: pnpm/action-setup@v2
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      - run: pnpm install
      - run: cd apps/api && pnpm test:run
      - run: pnpm test:e2e

Best Practices

  1. Isolation: Each test should be independent
  2. Clear Names: Use descriptive test names
  3. Arrange-Act-Assert: Structure tests clearly
  4. Mock External Dependencies: Don't hit real databases/APIs in unit tests
  5. Test Edge Cases: Test error conditions and boundary cases
  6. Keep Tests Fast: Unit tests should run quickly
  7. Maintainability: Update tests when code changes

Troubleshooting

Tests Failing

  1. Check if dependencies are installed: pnpm install
  2. Verify environment variables are set
  3. Check test database connection (for integration tests)
  4. Review test logs for specific error messages

E2E Tests Failing

  1. Ensure all services are running (API, client, admin)
  2. Check port configurations
  3. Verify test data exists in database
  4. Review browser console for errors

References

On this page