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

React测试报getItems[props.action] is not a function错误如何解决

问题解决方法

错误根因

你组件内部定义的getItems对象仅包含analysers、sites两个可调用的方法属性,但是测试代码中给SelectionList传递的action参数为空字符串,此时getItems[props.action]取值为undefined,对undefined做函数调用就会抛出对应的类型错误。

修复步骤

方案1:优化组件健壮性(推荐,同时避免线上出现同类问题)

  1. 收窄action属性的类型定义,从通用string改为明确的联合类型,提前规避非法参数传入:
interface SelectionListProps {
  // 其余属性保持不变
  action: 'analysers' | 'sites';
}
  1. 调用方法前增加合法性判断,同时补充useEffect缺失的依赖项避免闭包问题:
useEffect(() => {
  const actionHandler = getItems[props.action];
  if (typeof actionHandler === 'function') {
    actionHandler(props.actionArgs).then(() => {
      initializeCollapses();
    });
  }
}, [props.action, props.actionArgs, dispatch]);

方案2:直接修改测试用例,传入合法参数

测试时给action字段传入getItems中存在的key即可:

render(
  <Provider store={store}>
    <SelectionList
      classes={{ button_basic: "", formControl: "", selectionCard: "" }}
      action="sites" // 传入analysers也可
      actionArgs=""
    />
  </Provider>
);

任选以上一种方案都可以解决当前测试报错的问题,实现组件存在性校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:06:03