技能 编程开发 React 测试:Enzyme 到 RTL 迁移指南

React 测试:Enzyme 到 RTL 迁移指南

v20260410
react18-enzyme-to-rtl
本指南提供详细的模式,帮助开发者将 Enzyme 的单元测试迁移到 React Testing Library (RTL),尤其适用于升级到 React 18 的场景。核心在于理解测试理念的转变:从验证组件内部状态和实现细节,转变为模拟用户行为和验证可见输出。掌握 RTL 的最佳查询实践,确保你的测试能准确反映用户交互体验,编写出更健壮、更具可访问性的测试代码。
获取技能
118 次下载
概览

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
信息
Category 编程开发
Name react18-enzyme-to-rtl
版本 v20260410
大小 6.26KB
更新时间 2026-04-12
语言