Communitygithub.com

react-testing

Pruebas de componentes React con React Testing Library, Vitest/Jest, MSW para simulación de red, aserciones de accesibilidad con axe, y el límite entre pruebas de componentes y pruebas end-to-end con Playwright/Cypress. Úsalo al escribir o corregir pruebas para componentes React, hooks o páginas.

¿Qué es react-testing?

Este skill define un conjunto completo de patrones y mejores prácticas para realizar pruebas de componentes React, hooks y páginas, enfocándose en el comportamiento observable por el usuario en lugar de los detalles de implementación. Proporciona guías detalladas sobre la elección de librerías (Vitest vs Jest, Playwright Component Testing vs Cypress Component Testing), prioridad de queries (accesibles primero, test IDs como último recurso), interacciones con `userEvent`, patrones asíncronos, y simulación de red con MSW. Además, cubre la creación de wrappers de proveedores, pruebas de custom hooks, aserciones de accesibilidad con axe, y estrategias de cobertura. Incluye una clara delimitación de cuándo usar React Testing Library (componentes y lógica) frente a Playwright/Cypress (layout, animaciones, flujos completos E2E). Es compatible con proyectos que usan Vitest, Jest, Playwright o Cypress, y proporciona un flujo de trabajo TDD, ejemplos prácticos (formularios, límites de error, Suspense) y antipatrones a evitar.

Compatible con✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/react-testing

Preguntar en tu IA favorita

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

Documentación

Pruebas en React (React Testing)

Patrones completos de pruebas en React para pruebas de componentes centradas en el comportamiento, pruebas de hooks personalizados, aserciones de accesibilidad y simulación de red a nivel de red.

Cuándo activarlo

  • Escribiendo pruebas para componentes React, hooks personalizados o páginas.
  • Añadiendo cobertura de pruebas a componentes heredados no probados.
  • Migrando de Enzyme o patrones de la era de clases a React Testing Library.
  • Configurando Vitest o Jest para un nuevo proyecto React.
  • Simulando peticiones HTTP en pruebas.
  • Verificando violaciones de accesibilidad.
  • Decidiendo qué pruebas pertenecen a RTL vs Playwright Component Testing vs E2E completo.

Principio fundamental

Prueba lo que el usuario ve y hace, no los detalles de implementación.

Una prueba debería:

  • Renderizar el componente con los mismos proveedores que tiene en producción.
  • Interactuar con él mediante queries accesibles (role, label) y userEvent.
  • Verificar la salida visible y los efectos secundarios observables (callback ejecutado, petición enviada).

Una prueba NO debería:

  • Inspeccionar el estado del componente, las props pasadas a hijos o qué hooks se llamaron.
  • Simular (mockear) React o hooks del framework.
  • Verificar el número de renderizados o la estructura del DOM más allá de lo que afecta a los usuarios.

Elección de librería

EjecutorCuándoNota
VitestVite, Remix, configuraciones modernasMás rápido, ESM nativo, API compatible con Jest
JestNext.js, CRA, repositorios establecidosPredeterminado para muchos proyectos React
Playwright Component TestingSe necesita un motor de navegador realÚsalo cuando JSDOM carezca de la funcionalidad requerida
Cypress Component TestingNavegador real, Cypress ya en usoAlternativa a Playwright CT

Elige uno. No combines RTL + Vitest Y Playwright CT en el mismo repositorio a menos que tengas una separación clara de responsabilidades.

Prioridad de queries

React Testing Library expone queries en tres niveles. Úsalos de arriba abajo:

  1. Accesibles para todos: getByRole, getByLabelText, getByPlaceholderText, getByText, getByDisplayValue
  2. Semánticas: getByAltText, getByTitle
  3. Test IDs (vía de escape): getByTestId
// Mejor
screen.getByRole("button", { name: /save/i });

// Aceptable para inputs
screen.getByLabelText("Email");

// Último recurso
screen.getByTestId("save-btn");

Variantes:

  • getBy* — lanza una excepción si no encuentra coincidencia.
  • queryBy* — devuelve null (úsalo para "verificar ausencia").
  • findBy* — asíncrono, devuelve una Promesa (úsalo para elementos que aparecen después de trabajo asíncrono).

Interacción del usuario con userEvent

import userEvent from "@testing-library/user-event"

test("envía el formulario", async () => {
  const user = userEvent.setup()
  const onSubmit = vi.fn()
  render(<UserForm onSubmit={onSubmit} />)

  await user.type(screen.getByLabelText("Email"), "[email protected]")
  await user.click(screen.getByRole("button", { name: /save/i }))

  expect(onSubmit).toHaveBeenCalledWith({ email: "[email protected]" })
})
  • Siempre usa await en las llamadas a userEvent.
  • Llama a userEvent.setup() una vez por prueba y reutiliza el objeto user devuelto.
  • userEvent simula una secuencia real de navegador; fireEvent despacha un único evento sintético. Prefiere userEvent.

Patrones asíncronos

// Elemento que aparece después de trabajo asíncrono
expect(await screen.findByText("Cargado")).toBeInTheDocument()

// Verificación de efecto secundario
await waitFor(() => expect(saveSpy).toHaveBeenCalled())

// Elemento que debería desaparecer
await waitForElementToBeRemoved(() => screen.queryByText("Cargando"))

Nunca uses setTimeout + verificación: es inestable. Usa los matchers anteriores.

Simulación de red con MSW

Mock Service Worker simula a nivel de red. El componente, los hooks y la librería fetch se comportan exactamente como en producción.

Configuración

// test/setup.ts
import { setupServer } from "msw/node"
import { http, HttpResponse } from "msw"

export const handlers = [
  http.get("/api/users/:id", ({ params }) =>
    HttpResponse.json({ id: params.id, name: "Alice" }),
  ),
  http.post("/api/users", async ({ request }) => {
    const body = await request.json()
    return HttpResponse.json({ id: "new-id", ...body }, { status: 201 })
  }),
]

export const server = setupServer(...handlers)

beforeAll(() => server.listen({ onUnhandledRequest: "error" }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

Configura onUnhandledRequest: "error" para que cualquier petición no simulada haga fallar la prueba de forma ruidosa. Los pases silenciosos son peores que el rojo.

Anulación por prueba

test("muestra error en 500", async () => {
  server.use(
    http.get("/api/users/:id", () => new HttpResponse(null, { status: 500 }))
  )
  render(<UserPage id="1" />)
  expect(await screen.findByText(/algo salió mal/i)).toBeInTheDocument()
})

Envoltorio de proveedores (Provider Wrapping)

Envuelve los proveedores una vez en un archivo test-utils.tsx:

// test-utils.tsx
import { render, RenderOptions } from "@testing-library/react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"

export function renderWithProviders(
  ui: React.ReactElement,
  options?: RenderOptions,
) {
  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: false } },
  })

  return render(
    <QueryClientProvider client={queryClient}>
      <ThemeProvider theme={lightTheme}>
        <MemoryRouter>{ui}</MemoryRouter>
      </ThemeProvider>
    </QueryClientProvider>,
    options,
  )
}

export * from "@testing-library/react"

Luego importa import { renderWithProviders, screen } from "test-utils" en cada archivo de prueba.

Pruebas de hooks personalizados (Custom Hooks)

import { renderHook, act } from "@testing-library/react"

test("useCounter incrementa y decrementa", () => {
  const { result } = renderHook(() => useCounter(0))

  expect(result.current.count).toBe(0)

  act(() => result.current.increment())
  expect(result.current.count).toBe(1)

  act(() => result.current.decrement())
  expect(result.current.count).toBe(0)
})

test("useCounter acepta valor inicial", () => {
  const { result } = renderHook(() => useCounter(10))
  expect(result.current.count).toBe(10)
})

test("useUser obtiene datos de usuario", async () => {
  // Instancia QueryClient UNA VEZ por prueba fuera del wrapper para que sobreviva a los re-renderizados.
  // Crearlo dentro del closure del wrapper restablece el caché en cada renderizado, produciendo pruebas inestables.
  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: false } },
  })
  const wrapper = ({ children }: { children: React.ReactNode }) => (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  )

  const { result } = renderHook(() => useUser("1"), { wrapper })

  await waitFor(() => expect(result.current.isSuccess).toBe(true))
  expect(result.current.data).toEqual({ id: "1", name: "Alice" })
})
  • Envuelve las llamadas que cambian el estado en act.
  • Prueba solo a través de la API pública del hook.
  • Para hooks que usan contexto, pasa un wrapper.

Aserciones de accesibilidad (Accessibility Assertions)

import { axe, toHaveNoViolations } from "jest-axe"  // o vitest-axe
expect.extend(toHaveNoViolations)

test("UserCard no tiene violaciones de a11y", async () => {
  const { container } = render(<UserCard user={mockUser} />)
  expect(await axe(container)).toHaveNoViolations()
})

Ejecuta axe en pruebas de componentes para cada componente interactivo. Detecta:

  • Etiquetas faltantes en inputs de formularios.
  • Uso inválido de ARIA.
  • Contraste de color deficiente (limitado; JSDOM no tiene un motor CSS real, por lo que funciona solo para estilos en línea; el contraste visual pertenece a Playwright).
  • Texto alternativo faltante en imágenes.
  • Violaciones de orden de encabezados.

Enlace cruzado: skills/accessibility/SKILL.md para el manual de pruebas de accesibilidad más amplio.

Cuándo NO usar pruebas instantáneas (Snapshot Tests)

Las instantáneas de la salida renderizada:

  • Se rompen con cada cambio de estilo.
  • Se aprueban sin revisión durante el code review.
  • Prueban detalles de implementación (estructura del DOM), no comportamiento.

Usos aceptables de instantáneas:

  • Funciones de serialización de datos puras (formatInvoice(invoice) -> string estable).
  • Archivos de configuración generados (por ejemplo, salida de configuración de webpack).

Para regresión visual en componentes, usa capturas de pantalla de Playwright/Cypress o Percy/Chromatic (diferencias visuales reales, no strings del DOM).

Cuándo usar Playwright / Cypress

JSDOM (usado por Vitest/Jest) no puede:

  • Renderizar layout real (flexbox, grid, consultas de viewport).
  • Ejecutar animaciones nativas del navegador, transiciones CSS.
  • Probar comportamiento de scroll (desplazamiento), arrastrar y soltar, pegar desde el portapapeles.
  • Manejar iframes, ventanas emergentes, descargas, flujos de origen cruzado (cross-origin).
  • Ejecutar una red real en un entorno controlado con soporte completo de DevTools.

Para cualquiera de estos casos, usa Playwright Component Testing (prueba de componente en un navegador real) o E2E completo. Consulta e2e-testing skill.

Límite de decisión:

  • Un hook, un componente de presentación, un formulario con lógica -> RTL.
  • Un componente cuyo layout importa o que usa APIs del navegador que no están en JSDOM -> Playwright CT.
  • Un flujo de usuario completo a través de múltiples páginas -> Playwright/Cypress E2E.

Objetivos de cobertura

CapaObjetivo
Utilidades puras>=90%
Hooks personalizados>=85%
Componentes de presentación>=80% — comportamiento, no líneas
Componentes contenedores>=70% — caminos felices + estados de error
PáginasCubiertas por E2E por separado; mínimo prueba de humo

Configura mediante vitest.config.ts / jest.config.js:

// vitest.config.ts
test: {
  coverage: {
    provider: "v8",
    reporter: ["text", "html", "lcov"],
    thresholds: {
      lines: 80,
      functions: 80,
      branches: 70,
      statements: 80,
    },
  },
}

Antipatrones (Anti-Patterns)

  • container.querySelector("...") — evita las queries accesibles, permite que las pruebas pasen cuando los usuarios reales fallarían.
  • Verificar el número de renderizados — detalle de implementación.
  • jest.mock("react", ...) — nunca simules React. Refactoriza el componente en su lugar.
  • Simular componentes hijos por defecto — prueba la integración, no el aislamiento. Simula solo cuando el hijo tenga efectos secundarios pesados.
  • Ignorar las advertencias de act() — señalan errores reales (actualización de estado después de desmontar, envoltura asíncrona faltante).
  • Compartir estado mutable entre pruebas — se vuelven inestables cuando el orden de las pruebas cambia.
  • Pruebas que pasan con it.skip() eliminado — tu prueba no verifica realmente lo que crees.

Flujo de trabajo TDD

ROJO     -> Escribe una prueba fallida para el próximo requisito
VERDE    -> Escribe el código mínimo del componente para que pase
REFACTORIZAR -> Mejora el componente, las pruebas siguen en verde
REPETIR  -> Próximo requisito

Para componentes nuevos:

  1. Define el tipo de props y la firma del componente.
  2. Escribe la primera prueba para el caso más simple.
  3. Verifica que falla por la razón correcta.
  4. Implementa lo suficiente para que pase.
  5. Añade el siguiente caso de prueba.
  6. Refactoriza cuando la tercera prueba similar revele un patrón.

Comandos de prueba

# Vitest
vitest                            # modo watch
vitest run                        # ejecución única
vitest run --coverage             # con cobertura
vitest run path/to/file.test.tsx  # archivo único

# Jest
jest --watch
jest --coverage
jest path/to/file.test.tsx

# Modo CI
CI=true vitest run --coverage

Relacionados

Ejemplos

Envío de formulario con MSW y userEvent

test("envía el formulario de usuario y muestra éxito", async () => {
  server.use(
    http.post("/api/users", () =>
      HttpResponse.json({ id: "1", name: "Alice" }, { status: 201 })
    ),
  )

  const user = userEvent.setup()
  renderWithProviders(<UserForm />)

  await user.type(screen.getByLabelText("Nombre"), "Alice")
  await user.type(screen.getByLabelText("Email"), "[email protected]")
  await user.click(screen.getByRole("button", { name: /guardar/i }))

  expect(await screen.findByText(/guardado correctamente/i)).toBeInTheDocument()
})

Prueba de un límite de error (Error Boundary)

function Roto() {
  throw new Error("boom")
}

test("el límite de error renderiza el fallback", () => {
  // Suprime el ruido de console.error de React para el error esperado, luego restaura para que
  // el espía no se filtre entre pruebas y oculte errores reales en otros lugares.
  const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
  try {
    render(
      <ErrorBoundary fallback={<div>Algo salió mal</div>}>
        <Roto />
      </ErrorBoundary>,
    )

    expect(screen.getByText("Algo salió mal")).toBeInTheDocument()
  } finally {
    errorSpy.mockRestore()
  }
})

Prueba de un límite de Suspense

test("muestra cargando y luego contenido", async () => {
  renderWithProviders(
    <Suspense fallback={<div>Cargando...</div>}>
      <UserDetail id="1" />
    </Suspense>,
  )

  expect(screen.getByText("Cargando...")).toBeInTheDocument()
  expect(await screen.findByText("Alice")).toBeInTheDocument()
})

Individual skills in this repo

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

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Skills relacionados