SuperAPI AI 工具集

react18-enzyme-to-rtl

测试与质量

查看项目

更新于 10-14 15:21

技能介绍

用途

本技能用于 React 18 升级过程中将 Enzyme 测试迁移到 React Testing Library(RTL)。由于 Enzyme 没有 React 18 适配器,也没有 React 18 支持路径,所有 Enzyme 测试都必须使用 React Testing Library 重写。

核心理念

Enzyme 测试实现细节,RTL 测试行为。

示例对比:

// 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();

这不是 1:1 的翻译。验证内部状态或实例方法的 Enzyme 测试在 RTL 中没有等价物——因为 RTL 有意不暴露内部实现。应改为断言可见结果。

主要能力

  • 为每个 Enzyme API 提供完整的改写前后代码对照,参考文件 references/enzyme-api-map.md 包含完整映射:shallow、mount、find、simulate、prop、state、instance、configure。
  • 异步模式参考文件 references/async-patterns.md 涵盖 waitFor、findBy、act()、Apollo MockedProvider、加载状态、错误状态。

使用方式

核心重写模板规定了每个 Enzyme 测试重写后的形态:

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 查询优先级按以下顺序使用:

  1. getByRole - 匹配可访问角色(button、textbox、heading、checkbox 等)
  2. getByLabelText - 关联标签的表单字段
  3. getByPlaceholderText - 输入占位符
  4. getByText - 可见文本内容
  5. getByDisplayValue - input/select/textarea 的当前值
  6. getByAltText - 图片替代文本
  7. getByTitle - title 属性
  8. getByTestId - data-testid 属性(最后手段)

优先使用 getByRole 而非 getByTestId,因为 getByRole 同时测试可访问性。

使用 Provider 包裹的写法:

// 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

适用场景

适用于 React 18 升级中需要重写 Enzyme 测试的项目,尤其是涉及异步数据请求、Apollo、加载与错误状态、Provider 嵌套等测试场景。

限制

该技能只提供迁移改写模式,不提供 Enzyme 对 React 18 的支持路径。验证组件内部状态或实例方法的测试无法直接映射到 RTL,必须改写为对可见结果的断言。关于具体版本兼容性、安装命令、价格或其它平台支持信息,资料中暂未提供。