Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.
Test-Driven Development Workflow
This skill ensures all code development follows TDD principles with comprehensive test coverage.
When to Activate
- Writing new features or functionality
- Fixing bugs or issues
- Refactoring existing code
- Adding API endpoints
- Creating new components
Core Principles
1. Tests BEFORE Code
ALWAYS write tests first, then implement code to make tests pass.
2. Coverage Requirements
- Minimum 80% coverage (unit + integration + E2E)
- All edge cases covered
- Error scenarios tested
- Boundary conditions verified
3. Test Types
Unit Tests
- Individual functions and utilities
- Component logic
- Pure functions
- Helpers and utilities
Integration Tests
- API endpoints
- Database operations
- Service interactions
- External API calls
E2E Tests (Playwright)
- Critical user flows
- Complete workflows
- Browser automation
- UI interactions
TDD Workflow Steps
Step 1: Write User Journeys
1As a [role], I want to [action], so that [benefit]
2
3Example:
4As a user, I want to search for markets semantically,
5so that I can find relevant markets even without exact keywords.Step 2: Generate Test Cases
For each user journey, create comprehensive test cases:
1describe('Semantic Search', () => {
2 it('returns relevant markets for query', async () => {
3 // Test implementation
4 })
5
6 it('handles empty query gracefully', async () => {
7 // Test edge case
8 })
9
10 it('falls back to substring search when Redis unavailable', async () => {
11 // Test fallback behavior
12 })
13
14 it('sorts results by similarity score', async () => {
15 // Test sorting logic
16 })
17})Step 3: Run Tests (They Should Fail)
1npm test
2# Tests should fail - we haven't implemented yetStep 4: Implement Code
Write minimal code to make tests pass:
1// Implementation guided by tests
2export async function searchMarkets(query: string) {
3 // Implementation here
4}Step 5: Run Tests Again
1npm test
2# Tests should now passStep 6: Refactor
Improve code quality while keeping tests green:
- Remove duplication
- Improve naming
- Optimize performance
- Enhance readability
Step 7: Verify Coverage
1npm run test:coverage
2# Verify 80%+ coverage achievedTesting Patterns
Unit Test Pattern (Jest/Vitest)
1import { render, screen, fireEvent } from '@testing-library/react'
2import { Button } from './Button'
3
4describe('Button Component', () => {
5 it('renders with correct text', () => {
6 render(<Button>Click me</Button>)
7 expect(screen.getByText('Click me')).toBeInTheDocument()
8 })
9
10 it('calls onClick when clicked', () => {
11 const handleClick = jest.fn()
12 render(<Button onClick={handleClick}>Click</Button>)
13
14 fireEvent.click(screen.getByRole('button'))
15
16 expect(handleClick).toHaveBeenCalledTimes(1)
17 })
18
19 it('is disabled when disabled prop is true', () => {
20 render(<Button disabled>Click</Button>)
21 expect(screen.getByRole('button')).toBeDisabled()
22 })
23})API Integration Test Pattern
1import { NextRequest } from 'next/server'
2import { GET } from './route'
3
4describe('GET /api/markets', () => {
5 it('returns markets successfully', async () => {
6 const request = new NextRequest('http://localhost/api/markets')
7 const response = await GET(request)
8 const data = await response.json()
9
10 expect(response.status).toBe(200)
11 expect(data.success).toBe(true)
12 expect(Array.isArray(data.data)).toBe(true)
13 })
14
15 it('validates query parameters', async () => {
16 const request = new NextRequest('http://localhost/api/markets?limit=invalid')
17 const response = await GET(request)
18
19 expect(response.status).toBe(400)
20 })
21
22 it('handles database errors gracefully', async () => {
23 // Mock database failure
24 const request = new NextRequest('http://localhost/api/markets')
25 // Test error handling
26 })
27})E2E Test Pattern (Playwright)
1import { test, expect } from '@playwright/test'
2
3test('user can search and filter markets', async ({ page }) => {
4 // Navigate to markets page
5 await page.goto('/')
6 await page.click('a[href="/markets"]')
7
8 // Verify page loaded
9 await expect(page.locator('h1')).toContainText('Markets')
10
11 // Search for markets
12 await page.fill('input[placeholder="Search markets"]', 'election')
13
14 // Wait for debounce and results
15 await page.waitForTimeout(600)
16
17 // Verify search results displayed
18 const results = page.locator('[data-testid="market-card"]')
19 await expect(results).toHaveCount(5, { timeout: 5000 })
20
21 // Verify results contain search term
22 const firstResult = results.first()
23 await expect(firstResult).toContainText('election', { ignoreCase: true })
24
25 // Filter by status
26 await page.click('button:has-text("Active")')
27
28 // Verify filtered results
29 await expect(results).toHaveCount(3)
30})
31
32test('user can create a new market', async ({ page }) => {
33 // Login first
34 await page.goto('/creator-dashboard')
35
36 // Fill market creation form
37 await page.fill('input[name="name"]', 'Test Market')
38 await page.fill('textarea[name="description"]', 'Test description')
39 await page.fill('input[name="endDate"]', '2025-12-31')
40
41 // Submit form
42 await page.click('button[type="submit"]')
43
44 // Verify success message
45 await expect(page.locator('text=Market created successfully')).toBeVisible()
46
47 // Verify redirect to market page
48 await expect(page).toHaveURL(/\/markets\/test-market/)
49})Test File Organization
1src/
2├── components/
3│ ├── Button/
4│ │ ├── Button.tsx
5│ │ ├── Button.test.tsx # Unit tests
6│ │ └── Button.stories.tsx # Storybook
7│ └── MarketCard/
8│ ├── MarketCard.tsx
9│ └── MarketCard.test.tsx
10├── app/
11│ └── api/
12│ └── markets/
13│ ├── route.ts
14│ └── route.test.ts # Integration tests
15└── e2e/
16 ├── markets.spec.ts # E2E tests
17 ├── trading.spec.ts
18 └── auth.spec.tsMocking External Services
Supabase Mock
1jest.mock('@/lib/supabase', () => ({
2 supabase: {
3 from: jest.fn(() => ({
4 select: jest.fn(() => ({
5 eq: jest.fn(() => Promise.resolve({
6 data: [{ id: 1, name: 'Test Market' }],
7 error: null
8 }))
9 }))
10 }))
11 }
12}))Redis Mock
1jest.mock('@/lib/redis', () => ({
2 searchMarketsByVector: jest.fn(() => Promise.resolve([
3 { slug: 'test-market', similarity_score: 0.95 }
4 ])),
5 checkRedisHealth: jest.fn(() => Promise.resolve({ connected: true }))
6}))OpenAI Mock
1jest.mock('@/lib/openai', () => ({
2 generateEmbedding: jest.fn(() => Promise.resolve(
3 new Array(1536).fill(0.1) // Mock 1536-dim embedding
4 ))
5}))Test Coverage Verification
Run Coverage Report
1npm run test:coverageCoverage Thresholds
1{
2 "jest": {
3 "coverageThresholds": {
4 "global": {
5 "branches": 80,
6 "functions": 80,
7 "lines": 80,
8 "statements": 80
9 }
10 }
11 }
12}Common Testing Mistakes to Avoid
❌ WRONG: Testing Implementation Details
1// Don't test internal state
2expect(component.state.count).toBe(5)✅ CORRECT: Test User-Visible Behavior
1// Test what users see
2expect(screen.getByText('Count: 5')).toBeInTheDocument()❌ WRONG: Brittle Selectors
1// Breaks easily
2await page.click('.css-class-xyz')✅ CORRECT: Semantic Selectors
1// Resilient to changes
2await page.click('button:has-text("Submit")')
3await page.click('[data-testid="submit-button"]')❌ WRONG: No Test Isolation
1// Tests depend on each other
2test('creates user', () => { /* ... */ })
3test('updates same user', () => { /* depends on previous test */ })✅ CORRECT: Independent Tests
1// Each test sets up its own data
2test('creates user', () => {
3 const user = createTestUser()
4 // Test logic
5})
6
7test('updates user', () => {
8 const user = createTestUser()
9 // Update logic
10})Continuous Testing
Watch Mode During Development
1npm test -- --watch
2# Tests run automatically on file changesPre-Commit Hook
1# Runs before every commit
2npm test && npm run lintCI/CD Integration
1# GitHub Actions
2- name: Run Tests
3 run: npm test -- --coverage
4- name: Upload Coverage
5 uses: codecov/codecov-action@v3Best Practices
- Write Tests First - Always TDD
- One Assert Per Test - Focus on single behavior
- Descriptive Test Names - Explain what's tested
- Arrange-Act-Assert - Clear test structure
- Mock External Dependencies - Isolate unit tests
- Test Edge Cases - Null, undefined, empty, large
- Test Error Paths - Not just happy paths
- Keep Tests Fast - Unit tests < 50ms each
- Clean Up After Tests - No side effects
- Review Coverage Reports - Identify gaps
Success Metrics
- 80%+ code coverage achieved
- All tests passing (green)
- No skipped or disabled tests
- Fast test execution (< 30s for unit tests)
- E2E tests cover critical user flows
- Tests catch bugs before production
Remember: Tests are not optional. They are the safety net that enables confident refactoring, rapid development, and production reliability.