CommunityProgramación y desarrollogithub.com

testing-strategy

Testing strategies for production web applications — unit, integration, E2E testing with Jest, Vitest, pytest, Playwright, and testing patterns for React components, APIs, and databases.

¿Qué es testing-strategy?

testing-strategy is a Claude Code agent skill that testing strategies for production web applications — unit, integration, E2E testing with Jest, Vitest, pytest, Playwright, and testing patterns for React components, APIs, and databases.

Compatible con~Claude Code~Codex CLI~Cursor
Part ofReact
npx skills add https://github.com/CloudNinjaDev/claude-code-production-skills/tree/HEAD/skills/testing-strategy

Installed? Explore more Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Testing Strategy — Production Skill

Testing Pyramid

                    /\
                   /E2E\           Small number, slow, high confidence
                  /------\
                 /  Integ  \       Medium number, real dependencies
                /------------\
               /  Unit Tests  \    Many, fast, isolated
              /----------------\
  • Unit: Fast, isolated, mock dependencies. Test business logic.
  • Integration: Test with real DB, real HTTP. Test service layers.
  • E2E: Full browser automation. Test critical user journeys only.

JavaScript/TypeScript Testing

Vitest + React Testing Library

// vitest.config.ts
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
    globals: true,
    setupFiles: ['./src/test/setup.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'html'],
      thresholds: { lines: 80, functions: 80, branches: 80 }
    }
  }
})

// src/test/setup.ts
import '@testing-library/jest-dom'
import { afterEach } from 'vitest'
import { cleanup } from '@testing-library/react'

afterEach(cleanup)

Unit Tests

// lib/utils.test.ts
import { describe, it, expect } from 'vitest'
import { formatPrice, calculateDiscount, paginate } from './utils'

describe('formatPrice', () => {
  it('formats cents to dollar string', () => {
    expect(formatPrice(1999)).toBe('$19.99')
    expect(formatPrice(0)).toBe('$0.00')
    expect(formatPrice(100000)).toBe('$1,000.00')
  })

  it('handles negative values', () => {
    expect(formatPrice(-500)).toBe('-$5.00')
  })
})

describe('calculateDiscount', () => {
  it('applies percentage discount', () => {
    expect(calculateDiscount(1000, 10)).toBe(900)
  })

  it('does not go below zero', () => {
    expect(calculateDiscount(100, 150)).toBe(0)
  })
})

describe('paginate', () => {
  const items = Array.from({ length: 25 }, (_, i) => i)

  it.each([
    [1, 10, items.slice(0, 10)],
    [2, 10, items.slice(10, 20)],
    [3, 10, items.slice(20, 25)],
  ])('returns page %i', (page, perPage, expected) => {
    expect(paginate(items, page, perPage)).toEqual(expected)
  })
})

Component Tests

// components/UserCard.test.tsx
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { vi, describe, it, expect } from 'vitest'
import { UserCard } from './UserCard'

const mockUser = { id: '1', name: 'Alice Smith', email: '[email protected]', role: 'admin' }

describe('UserCard', () => {
  it('renders user information', () => {
    render(<UserCard user={mockUser} />)
    expect(screen.getByText('Alice Smith')).toBeInTheDocument()
    expect(screen.getByText('[email protected]')).toBeInTheDocument()
    expect(screen.getByRole('badge', { name: /admin/i })).toBeInTheDocument()
  })

  it('calls onDelete when delete button clicked', async () => {
    const user = userEvent.setup()
    const onDelete = vi.fn()
    
    render(<UserCard user={mockUser} onDelete={onDelete} />)
    
    await user.click(screen.getByRole('button', { name: /delete/i }))
    
    // Confirm dialog
    await user.click(screen.getByRole('button', { name: /confirm/i }))
    
    expect(onDelete).toHaveBeenCalledWith('1')
    expect(onDelete).toHaveBeenCalledTimes(1)
  })

  it('shows loading state while deleting', async () => {
    const user = userEvent.setup()
    const onDelete = vi.fn().mockImplementation(() => new Promise(r => setTimeout(r, 1000)))
    
    render(<UserCard user={mockUser} onDelete={onDelete} />)
    await user.click(screen.getByRole('button', { name: /delete/i }))
    await user.click(screen.getByRole('button', { name: /confirm/i }))
    
    expect(screen.getByRole('button', { name: /deleting/i })).toBeDisabled()
  })
})

Mocking Patterns

// Mock Next.js router
import { vi } from 'vitest'
vi.mock('next/navigation', () => ({
  useRouter: () => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn() }),
  usePathname: () => '/',
  useSearchParams: () => new URLSearchParams(),
}))

// Mock fetch
global.fetch = vi.fn()
vi.mocked(fetch).mockResolvedValue({
  ok: true,
  json: async () => ({ data: mockData }),
} as Response)

// Mock module
vi.mock('@/lib/db', () => ({
  db: {
    user: {
      findMany: vi.fn().mockResolvedValue([mockUser]),
      create: vi.fn().mockResolvedValue(mockUser),
    }
  }
}))

// Spy on method
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
// ... test ...
expect(consoleSpy).not.toHaveBeenCalled()
consoleSpy.mockRestore()

API Route Tests (Next.js)

// app/api/users/__tests__/route.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { GET, POST } from '../route'
import { db } from '@/lib/db'

vi.mock('@/lib/db')
vi.mock('@/lib/auth', () => ({ auth: vi.fn().mockResolvedValue({ user: { id: '1', role: 'admin' } }) }))

describe('GET /api/users', () => {
  it('returns list of users', async () => {
    vi.mocked(db.user.findMany).mockResolvedValue([mockUser])
    
    const response = await GET(new Request('http://localhost/api/users'))
    const data = await response.json()
    
    expect(response.status).toBe(200)
    expect(data).toHaveLength(1)
    expect(data[0].email).toBe(mockUser.email)
  })

  it('returns 401 when unauthenticated', async () => {
    vi.mocked(auth).mockResolvedValueOnce(null)
    const response = await GET(new Request('http://localhost/api/users'))
    expect(response.status).toBe(401)
  })
})

Python Testing (pytest)

# conftest.py
import pytest
import pytest_asyncio
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker

from app.main import app
from app.core.database import get_db, Base

@pytest_asyncio.fixture(scope="session")
async def engine():
    engine = create_async_engine("postgresql+asyncpg://test:test@localhost:5432/testdb")
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield engine
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await engine.dispose()

@pytest_asyncio.fixture
async def db(engine):
    session_factory = async_sessionmaker(engine, expire_on_commit=False)
    async with session_factory() as session:
        yield session
        await session.rollback()  # Clean up after each test

@pytest_asyncio.fixture
async def client(db):
    app.dependency_overrides[get_db] = lambda: db
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
        yield ac
    app.dependency_overrides.clear()

@pytest.fixture
def mock_user(db):
    # Create a test user in DB
    ...

# tests/test_users.py
import pytest

class TestUserEndpoints:
    async def test_get_user_success(self, client, mock_user, auth_headers):
        response = await client.get(f"/api/v1/users/{mock_user.id}", headers=auth_headers)
        assert response.status_code == 200
        assert response.json()["email"] == mock_user.email

    async def test_get_user_not_found(self, client, auth_headers):
        response = await client.get("/api/v1/users/99999", headers=auth_headers)
        assert response.status_code == 404

    async def test_create_user_duplicate_email(self, client, mock_user):
        response = await client.post("/api/v1/users/", json={
            "email": mock_user.email,
            "password": "password123"
        })
        assert response.status_code == 400

    @pytest.mark.parametrize("email,password,expected_status", [
        ("not-an-email", "password123", 422),
        ("[email protected]", "short", 422),
        ("[email protected]", "validpassword", 201),
    ])
    async def test_create_user_validation(self, client, email, password, expected_status):
        response = await client.post("/api/v1/users/", json={"email": email, "password": password})
        assert response.status_code == expected_status

E2E Testing (Playwright)

// playwright.config.ts
import { defineConfig, devices } from '@playwright/test'

export default defineConfig({
  testDir: './e2e',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  reporter: 'html',
  use: {
    baseURL: 'http://localhost:3000',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'Mobile Chrome', use: { ...devices['Pixel 5'] } },
  ],
  webServer: {
    command: 'npm run dev',
    url: 'http://localhost:3000',
    reuseExistingServer: !process.env.CI,
  },
})

// e2e/auth.spec.ts
import { test, expect } from '@playwright/test'

test.describe('Authentication', () => {
  test('user can sign in with valid credentials', async ({ page }) => {
    await page.goto('/login')
    
    await page.getByLabel('Email').fill('[email protected]')
    await page.getByLabel('Password').fill('password123')
    await page.getByRole('button', { name: 'Sign In' }).click()
    
    await expect(page).toHaveURL('/dashboard')
    await expect(page.getByText('Welcome back')).toBeVisible()
  })

  test('shows error for invalid credentials', async ({ page }) => {
    await page.goto('/login')
    await page.getByLabel('Email').fill('[email protected]')
    await page.getByLabel('Password').fill('wrongpassword')
    await page.getByRole('button', { name: 'Sign In' }).click()
    
    await expect(page.getByRole('alert')).toContainText('Invalid credentials')
    await expect(page).toHaveURL('/login')
  })
})

// Page Object Model for reusability
class LoginPage {
  constructor(private page: Page) {}

  async login(email: string, password: string) {
    await this.page.goto('/login')
    await this.page.getByLabel('Email').fill(email)
    await this.page.getByLabel('Password').fill(password)
    await this.page.getByRole('button', { name: 'Sign In' }).click()
  }
}

// Authenticated tests with stored state
// playwright/.auth/user.json (gitignored)
test.use({ storageState: 'playwright/.auth/user.json' })

What to Test

Test TypeWhat to Cover
UnitPure functions, utilities, calculations, data transformations
ComponentRendering, user interactions, form submissions, conditional display
IntegrationAPI routes with DB, auth flows, webhook processing
E2ESign up, sign in, purchase flow, core user journeys

What NOT to Test

  • Implementation details (test behavior, not internals)
  • Library code (Stripe, Prisma — they have their own tests)
  • Simple passthroughs with no logic
  • Exact styling/CSS (use visual regression tools instead)

CI Test Configuration

# .github/workflows/test.yml
name: Tests

on: [push, pull_request]

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '22', cache: 'npm' }
      - run: npm ci
      - run: npm run typecheck
      - run: npm run test:coverage
      - uses: codecov/codecov-action@v4

  e2e:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env: { POSTGRES_PASSWORD: test, POSTGRES_DB: testdb }
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '22', cache: 'npm' }
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npm run db:migrate:test
      - run: npx playwright test
      - uses: actions/upload-artifact@v4
        if: failure()
        with:
          name: playwright-report
          path: playwright-report/

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

Skills relacionados