Skip to content

Enzyme 方法不 找到 (React 测试)

错误信息

                TypeError: wrapper.查找(...).simulate 是不 函数
              

快速摘要

测试 uses Enzyme APIs (查找, simulate, shallow) 但 Enzyme 是不 安装, 不配置, or 方法 doesn't exist on wrapper.

为什么发生

  • Enzyme 是不 安装 in 项目.

  • Enzyme adapter for React version 是不 配置.

  • 方法 doesn't exist on wrapper 类型 (shallow 对比 mount).

  • Migrating 从 Enzyme 到 React 测试库 但 still using Enzyme APIs.

最小示例

✗ 错误代码
import { shallow } from 'enzyme';
// enzyme not installed
const wrapper = shallow(<Component />);
wrapper.find('button').simulate('click'); // TypeError
✓ 修复代码
// Migrate to React Testing Library
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
render(<Component />);
await userEvent.click(screen.getByRole('button'));

Migrate 从 Enzyme 到 React 测试库, 哪个是 modern 标准.

如何诊断

  • 检查如果 enzyme and enzyme-adapter-react-N 是 in 包.JSON.

  • 检查如果 Enzyme adapter 是配置 (enzyme.配置({ adapter: 新 Adapter() })).

  • 验证方法 exists on wrapper 类型是 used.

  • Consider migrating 到 React 测试库 (recommended for modern React).

如何修复

  • 安装 Enzyme and 正确 adapter: npm 安装 --保存-dev enzyme enzyme-adapter-react-18.

  • 配置 adapter in 设置 file.

  • Or migrate 到 React 测试库: use 渲染, screen.getByRole, userEvent 相反.

如何预防

  • For 新 React 项目, use React 测试库 相反的 Enzyme.

  • 如果 using Enzyme, ensure adapter matches 你的 React version.

相关资源

相关术语

相关课程

← 返回语言