You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试React下拉表单组件 修复用例报错提升测试覆盖率

React下拉组件点击事件测试失败解决方案

核心错误点

  • 渲染方式和查询API不匹配:你用Enzyme的shallow做浅渲染,但查询用的是React Testing Library的getByText,二者API不兼容;且shallow只会渲染当前组件第一层,不会渲染子组件内容,自然找不到foo元素
  • 方法名拼写错误:getBytext的t要大写,正确写法是getByText
  • 回调函数未传入:测试用例里验证handleOnChange被调用,但你初始化组件的时候没有把这个mock函数传给DropdownForm的对应props
  • 下拉选项数据源问题:你没有确认传入的choices数组里是否包含foo、bar这两个选项,如果数据源不对也会查不到对应元素
  • API废弃问题:waitForElement已经在新版React Testing Library中被废弃,建议改用waitFor

修正后的测试代码(统一使用React Testing Library实现)

// 提前导入依赖
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import DropdownForm from './DropdownForm';

// 提前定义mock数据和mock回调
const mockChoices = [
  { label: 'foo', value: 'foo' },
  { label: 'bar', value: 'bar' },
  { label: '其他选项', value: 'other' }
];
const mockLabel = '测试下拉框';
const mockHandleChange = jest.fn();

describe("DropdownForm", () => {
    it("should match snapshot", () => {
        const { asFragment } = render(<DropdownForm choices={mockChoices} label={mockLabel} onChange={mockHandleChange} />);
        expect(asFragment()).toMatchSnapshot();
    });

    it("should list the number of dropdown options", () => {
        render(<DropdownForm choices={mockChoices} label={mockLabel} onChange={mockHandleChange} />);
        fireEvent.click(screen.getByText('foo'));
        expect(screen.getAllByRole('option').length).toEqual(3);
    });

    it("should click on the dropdown menu", async () => {
        render(<DropdownForm choices={mockChoices} label={mockLabel} onChange={mockHandleChange} />);
        const dropdownTrigger = screen.getByText("foo");
        fireEvent.click(dropdownTrigger);
        const option = await waitFor(() => screen.getByText("bar"));
        fireEvent.click(option);
        expect(mockHandleChange).toHaveBeenCalledTimes(1);
    });
});

兼容Enzyme的替代方案

如果你坚持要用Enzyme做测试,就不要混入React Testing Library的查询方法,把shallow换成mount做全渲染,改用Enzyme自带的find方法查询元素即可。

内容的提问来源于stack exchange,提问作者HangoutGuy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:39:01