react18-enzyme-to-rtl

por github

Proporciona patrones exactos de migración de Enzyme a React Testing Library para actualizaciones a React 18. Usa esta habilidad siempre que sea necesario reescribir pruebas de Enzyme - shallow,…

npx skills add https://github.com/github/awesome-copilot --skill react18-enzyme-to-rtl

React 18 Enzyme → RTL Migration

Enzyme has no React 18 adapter and no React 18 support path. All Enzyme tests must be rewritten using React Testing Library.

The Philosophy Shift (Read This First)

Enzyme tests implementation. RTL tests behavior.

// Enzyme: tests that the component has the right internal state
expect(wrapper.state('count')).toBe(3);
expect(wrapper.instance().handleClick).toBeDefined();
expect(wrapper.find('Button').prop('disabled')).toBe(true);

// RTL: tests what the user actually sees and can do
expect(screen.getByText('Count: 3')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /submit/i })).toBeDisabled();

This is not a 1:1 translation. Enzyme tests that verify internal state or instance methods don't have RTL equivalents - because RTL intentionally doesn't expose internals. Rewrite the test to assert the visible outcome instead.

API Map

For complete before/after code for each Enzyme API, read:

  • references/enzyme-api-map.md - full mapping: shallow, mount, find, simulate, prop, state, instance, configure
  • references/async-patterns.md - waitFor, findBy, act(), Apollo MockedProvider, loading states, error states

Core Rewrite Template

// Every Enzyme test rewrites to this shape:
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MyComponent from './MyComponent';

describe('MyComponent', () => {
  it('does the thing', async () => {
    // 1. Render (replaces shallow/mount)
    render(<MyComponent prop="value" />);

    // 2. Query (replaces wrapper.find())
    const button = screen.getByRole('button', { name: /submit/i });

    // 3. Interact (replaces simulate())
    await userEvent.setup().click(button);

    // 4. Assert on visible output (replaces wrapper.state() / wrapper.prop())
    expect(screen.getByText('Submitted!')).toBeInTheDocument();
  });
});

RTL Query Priority (use in this order)

  1. getByRole - matches accessible roles (button, textbox, heading, checkbox, etc.)
  2. getByLabelText - form fields linked to labels
  3. getByPlaceholderText - input placeholders
  4. getByText - visible text content
  5. getByDisplayValue - current value of input/select/textarea
  6. getByAltText - image alt text
  7. getByTitle - title attribute
  8. getByTestId - data-testid attribute (last resort)

Prefer getByRole over getByTestId. It tests accessibility too.

Wrapping with Providers

// Enzyme with context:
const wrapper = mount(
  <ApolloProvider client={client}>
    <ThemeProvider theme={theme}>
      <MyComponent />
    </ThemeProvider>
  </ApolloProvider>
);

// RTL equivalent (use your project's customRender or wrap inline):
import { render } from '@testing-library/react';
render(
  <MockedProvider mocks={mocks} addTypename={false}>
    <ThemeProvider theme={theme}>
      <MyComponent />
    </ThemeProvider>
  </MockedProvider>
);
// Or use the project's customRender helper if it wraps providers

Más skills de github

console-rendering
github
Instrucciones para usar el sistema de renderizado en consola basado en etiquetas de struct en Go
official
acquire-codebase-knowledge
github
Usa esta habilidad cuando el usuario solicite explícitamente mapear, documentar o incorporarse a un código base existente. Actívala para indicaciones como "mapea este código base", "documenta…
official
acreadiness-assess
github
Run the AgentRC readiness assessment on the current repository and produce a static HTML dashboard at reports/index.html. Wraps `npx github:microsoft/agentrc…
official
acreadiness-generate-instructions
github
Genera archivos de instrucciones de agente de IA personalizados mediante el comando de instrucciones de AgentRC. Produce .github/copilot-instructions.md (por defecto, recomendado para Copilot en VS…)
official
acreadiness-policy
github
Ayudar al usuario a seleccionar, redactar o aplicar una política de AgentRC. Las políticas personalizan la puntuación de readiness desactivando comprobaciones irrelevantes, anulando impacto/nivel, estableciendo…
official
add-educational-comments
github
Añade comentarios educativos a archivos de código para convertirlos en recursos de aprendizaje efectivos. Adapta la profundidad y el tono de las explicaciones a tres niveles de conocimiento configurables: principiante, intermedio y avanzado. Solicita automáticamente un archivo si no se proporciona ninguno, con una lista numerada para una selección rápida. Expande los archivos hasta un 125% utilizando solo comentarios educativos (límite estricto: 400 líneas nuevas; 300 para archivos de más de 1,000 líneas). Conserva la codificación del archivo, el estilo de sangría, la corrección sintáctica y...
official
adobe-illustrator-scripting
github
Escribir, depurar y optimizar scripts de automatización de Adobe Illustrator usando ExtendScript (JavaScript/JSX). Úselo al crear o modificar scripts que manipulen…
official
agent-governance
github
Políticas declarativas, clasificación de intenciones y registros de auditoría para controlar el acceso y comportamiento de herramientas de agentes de IA. Las políticas de gobernanza componibles definen herramientas permitidas/bloqueadas, filtros de contenido, límites de velocidad y requisitos de aprobación, almacenados como configuración, no como código. La clasificación semántica de intenciones detecta indicaciones peligrosas (exfiltración de datos, escalada de privilegios, inyección de indicaciones) antes de la ejecución de herramientas mediante señales basadas en patrones. El decorador de gobernanza a nivel de herramienta aplica políticas en funciones...
official