Lección 10 de 11
Debugging y Testing con IA
Debugging Asistido por IA
Las IAs son excepcionales para debugging. Aprende técnicas profesionales.
Anatomía de un Bug Report para IA
// ❌ Malo:
"No funciona el login"
// ✅ Bueno:
"Error al hacer login:
Error exacto:
TypeError: Cannot read property userId of null
at AuthService.validateToken (auth.ts:45)
Código relevante:
[pegar función completa]
Pasos para reproducir:
1. Usuario ingresa credentials
2. Click en Login
3. Error en consola
Contexto:
- Next.js 14 + NextAuth
- Ocurre solo con Google OAuth
- Email/password funciona OK
- Desde deploy de ayer
Intenté:
- Limpiar cookies
- Revisar env vars
- Logs muestran token válido
¿Qué está pasando?"Debugging con Copilot Chat
// Inline debugging:
// 1. Selecciona función con bug
// 2. Ctrl+I
// 3. "/fix encuentra el bug"
// Copilot:
"Bug en línea 23:
No validas si response existe antes de .json()
Si fetch falla, response es undefined.
Fix:
[código corregido]"Debugging con Cursor
// Cmd+L con contexto:
"Debugging performance issue:
Problema:
- UserList muy lento con 500+ users
- Scroll laggy
- CPU spike al filtrar
Profiler muestra:
[screenshot o pegar profiler output]
@UserList.tsx
@useUsers.ts
¿Cuál es el bottleneck y cómo optimizar?"
// Cursor analiza archivos mencionados:
"Encontré 3 problemas:
1. CRÍTICO - Línea 34 UserList.tsx:
Filter ejecuta en cada render
FIX: useMemo
2. ALTO - useUsers.ts línea 12:
No hay pagination
FIX: Implementar virtual scroll
3. MEDIO - UserCard componente:
No está memoizado
FIX: React.memo
[Código optimizado para cada uno]"Debugging con Claude
// Para bugs complejos:
"Bug misterioso en producción:
Síntomas:
- Solo afecta 5% de usuarios
- No reproducible en dev
- Stack trace incompleto
- Ocurre aleatoriamente
Logs:
[pegar logs relevantes]
Código del área sospechosa:
[pegar código]
Diferencias prod vs dev:
- Prod: Node 20, Dev: Node 18
- Prod: PostgreSQL 15, Dev: 14
- Prod: 50K+ records, Dev: 100
¿Posibles causas? ¿Cómo investigar?"
// Claude hace análisis profundo:
"Análisis:
CAUSA PROBABLE: Race condition
Evidencia:
1. Logs muestran requests concurrentes
2. Código no es thread-safe (línea 67)
3. Solo se ve con muchos users (prod scale)
EXPLICACIÓN:
[explicación detallada]
CÓMO REPRODUCIR:
[script para simular concurrencia]
FIX:
[código con locks/atomic operations]
TESTS:
[tests de concurrencia]"Testing con IA
Generación de Tests
// Función a testear:
function calculateShipping(items, address) {
const weight = items.reduce((sum, item) => {
return sum + (item.weight * item.quantity);
}, 0);
const baseRate = address.country === "US" ? 5 : 15;
const weightRate = weight * 0.5;
const total = baseRate + weightRate;
// Free shipping over $100
const subtotal = items.reduce((sum, item) => {
return sum + (item.price * item.quantity);
}, 0);
return subtotal >= 100 ? 0 : total;
}
// Copilot Chat: "/tests"
// Genera suite completa:
describe("calculateShipping", () => {
it("calculates base shipping for US", () => {
const items = [{ weight: 2, quantity: 1, price: 50 }];
const address = { country: "US" };
expect(calculateShipping(items, address)).toBe(6); // 5 + 1
});
it("calculates base shipping for international", () => {
const items = [{ weight: 2, quantity: 1, price: 50 }];
const address = { country: "CA" };
expect(calculateShipping(items, address)).toBe(16); // 15 + 1
});
it("applies free shipping over 100", () => {
const items = [{ weight: 5, quantity: 1, price: 150 }];
const address = { country: "US" };
expect(calculateShipping(items, address)).toBe(0);
});
it("handles multiple items", () => {
const items = [
{ weight: 1, quantity: 2, price: 20 },
{ weight: 3, quantity: 1, price: 30 }
];
const address = { country: "US" };
// weight: (1*2) + (3*1) = 5
// rate: 5 + (5 * 0.5) = 7.5
expect(calculateShipping(items, address)).toBe(7.5);
});
it("handles edge cases", () => {
expect(calculateShipping([], { country: "US" })).toBe(5);
});
});Tests de Integración
// Cursor Composer:
"Crear suite de integration tests para:
Feature: User Authentication
Flujos a testear:
1. Signup completo
2. Login email/password
3. Login OAuth (mock)
4. Logout
5. Session persistence
6. Password reset
7. Email verification
Setup:
- Test DB (Prisma)
- Mock email service
- Supertest para API
Incluir:
- Setup/teardown
- Factories para data
- Assertions completas
- Coverage > 90%"
// Cursor genera archivo completo:
// ✓ describe blocks organizados
// ✓ beforeEach/afterEach
// ✓ Factories
// ✓ Mocks
// ✓ Tests exhaustivosE2E Tests
// ChatGPT:
"Genera E2E tests con Playwright para:
User journey: Compra completa
1. Landing page
2. Browse products
3. Add to cart (2 items)
4. Checkout
5. Enter shipping
6. Mock payment
7. Confirmation
8. Verify email sent
Incluir:
- Page objects pattern
- Screenshots on fail
- Video recording
- Accessibility checks
- Mobile viewport test"
// GPT genera estructura completaTDD con IA
// Test-Driven Development workflow:
// 1. Describe feature a IA:
"Need function to validate credit card:
- Accepts Visa, MC, Amex
- Luhn algorithm
- Expiry date validation
- CVV length by card type
Genera tests primero (TDD)"
// 2. IA genera tests:
describe("validateCreditCard", () => {
// ... tests completos
});
// 3. Tests fallan (función no existe)
// 4. Pide implementación:
"Implementa función que pase estos tests"
// 5. IA genera implementación
// 6. Run tests → ✅
// 7. Refactor si necesario:
"Refactoriza para mejor performance
sin romper tests"Debugging de Tests
// Test falla:
"Test fallando:
Expected: { success: true }
Received: { success: false, error: ... }
Test:
[código del test]
Function siendo testeada:
[código]
Logs:
[output relevante]
¿Por qué falla?"
// IA identifica problema exactoProperty-Based Testing
// ChatGPT:
"Genera property-based tests con fast-check
para función de sorting:
[función]
Properties:
1. Output length = input length
2. Output contiene mismos elementos
3. Order correcto
4. Idempotent (sort(sort(x)) = sort(x))
5. Handles duplicates
6. Empty array
Genera 100+ test cases aleatorios"Test Coverage Analysis
// Cursor:
"Analiza coverage de tests:
@src/services/UserService.ts
Coverage report:
[pegar istanbul/c8 output]
Identifica:
1. Uncovered lines
2. Edge cases missing
3. Error paths not tested
4. Genera tests para gaps"Mocking con IA
// Generar mocks complejos:
"Crear mocks para:
1. Prisma client (CRUD users)
2. Stripe API (payment flow)
3. SendGrid (emails)
4. Redis cache
Usar: Vitest vi.mock
Mocks deben:
- Simular responses reales
- Permitir assertions
- Error cases
- TypeScript types"Workflow Completo
// Development con IA:
1. Write test (con IA)
↓
2. Implement feature (Copilot autocomplete)
↓
3. Debug si falla (Cursor/Claude)
↓
4. Refactor (Copilot suggestions)
↓
5. More tests (IA genera edge cases)
↓
6. Coverage check (IA identifica gaps)
↓
7. Deploy con confidenceIA = debugging 10x más rápido, tests comprehensivos sin esfuerzo.