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

React Testing Library测试Ant Design下拉框时函数未调用问题

问题:Ant Design Select组件测试时点击选项未触发onChange绑定的mock函数

组件关键代码

<Select
  data-testid="addCompany"
  showSearch
  style={{ width: '100%' }}
  onChange={(value) =>
    onAddCompanySelectHandler(periodIndex, value)
  }
  placeholder="Add Company"
  value={companyDropdownValue}
  options={companyDropdownList}
/>

测试代码

const companyDropdownList = companies; // 来自模拟数据

describe('Test BaselineItemDetailsEdit component', () => {
  const onAddCompanySelectHandler = jest.fn();

  const editProps = {
    companyDropdownList,
    onAddCompanySelectHandler
 };

it.only('calls add Company from dropdown', async () => {
  render(<Component {...props} />);
  const company = screen.getByText('Company Name');
  userEvent.click(company);
  expect(onAddCompanySelectHandler).toBeCalled();
});

报错信息

● Test ItemDetails component › calls add Company from dropdown

expect(jest.fn()).toBeCalled()

Expected number of calls: >= 1
Received number of calls:    0

   95 |     const company = screen.getByText('Company Name');
   96 |     userEvent.click(company);
>  97 |     expect(onAddCompanySelectHandler).toBeCalled();
       |                                       ^
   98 |   });
   99 | });
  100 |

解决方法

  • 修正props传递错误:测试代码中定义了editProps但渲染组件时使用了{...props},导致mock函数未传入组件。将渲染代码改为:

    render(<Component {...editProps} />);
    
  • 正确触发Select组件的选择流程:Ant Design Select是封装组件,直接点击选项文本可能无法触发onChange,需先打开下拉框再选择:

    it.only('calls add Company from dropdown', async () => {
      render(<Component {...editProps} />);
      // 点击Select组件打开下拉面板
      const select = screen.getByTestId('addCompany');
      userEvent.click(select);
      // 等待选项渲染完成
      const companyOption = await screen.findByText('Company Name');
      // 点击选项
      userEvent.click(companyOption);
      // 或使用userEvent.selectOptions直接选择
      // userEvent.selectOptions(select, 'Company Name');
      expect(onAddCompanySelectHandler).toBeCalled();
    });
    
  • 验证options结构正确性:确保companyDropdownList是{ label: string, value: any }格式的数组,否则选项无法正确绑定value,导致onChange无法触发。

  • 确认periodIndex的有效性:组件中onChange调用onAddCompanySelectHandler(periodIndex, value),需确保测试环境中periodIndex是有效参数,避免因参数问题导致函数未正确执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:55:29