Backend Testing
Testing API endpoints and database operations
๐ Overview
This guide covers testing tRPC procedures, database queries, and API endpoints.
๐งช Setup
cd apps/api
pnpm add -D vitest @testcontainers/postgresql
๐ Testing tRPC Procedures
import { describe, it, expect } from 'vitest'
import { appRouter } from '@izri/trpc/routers'
import { createTestContext } from './utils'
describe('projectsRouter', () => {
it('lists user projects', async () => {
const ctx = await createTestContext()
const caller = appRouter.createCaller(ctx)
const projects = await caller.projects.list()
expect(projects).toEqual([])
})
it('creates a project', async () => {
const ctx = await createTestContext()
const caller = appRouter.createCaller(ctx)
const project = await caller.projects.create({
name: 'Test Project',
repository: 'https://github.com/test/repo',
})
expect(project.name).toBe('Test Project')
})
})
๐๏ธ Database Testing
import { PostgreSqlContainer } from '@testcontainers/postgresql'
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
let container: PostgreSqlContainer
beforeAll(async () => {
container = await new PostgreSqlContainer().start()
const connection = postgres(container.getConnectionUri())
const db = drizzle(connection)
// Run migrations
await migrate(db, { migrationsFolder: './migrations' })
}, 60000)
afterAll(async () => {
await container.stop()
})
๐ Test Utilities
// test/utils.ts
export async function createTestContext() {
const db = await getTestDatabase()
const userId = 'test-user-' + Math.random()
return {
db,
userId,
}
}
๐ Running Tests
# Run all tests
pnpm test
# Watch mode
pnpm test:watch
# Coverage
pnpm test:coverage
๐ Related Documentation
- Testing Guide - General testing
- tRPC Server - tRPC patterns
- Database Queries - Database patterns
Section 05 (Backend) complete! Next: Packages documentation