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

React组件测试报错:e.target.getAttribute is not a function

解决React组件测试中e.target.getAttribute is not a function错误

你遇到的这个错误根源很明确:你手动模拟的事件对象里的target只是一个普通JavaScript对象,并不具备真实DOM元素才有的getAttribute方法,但你的getValue工具函数却调用了这个方法,自然会触发类型错误。

下面给你两种可行的解决思路:

方案一:给模拟事件对象添加getAttribute方法

既然你的getValue依赖这个方法,那就在模拟的target里实现它。比如:

it('should call the onChange for the input element', () => {
  const event = {
    target: {
      name: "pollName",
      value: "spam",
      // 实现getAttribute方法,返回对应属性
      getAttribute: function(attr) {
        return this[attr];
      }
    }
  };
  const input = shallow(<Input onChange={getValue} />)
  input.simulate('change', event)
})

这样当getValue调用e.target.getAttribute('name')时,就能正确拿到pollName的值了。

方案二:优化getValue函数,直接使用e.target.name

其实在React的合成事件体系中,e.target.name是可以直接获取的,完全不需要借助getAttribute方法。这种方式更符合React的使用习惯,还能让你的工具函数更简洁,同时避免依赖DOM API,测试起来也更省心。修改后的getValue:

export const getValue = e => ({ 
  name: e.target.name, 
  value: e.target.value 
})

修改后,你原来的测试代码不需要做任何改动就能正常运行,因为你模拟的event.target.name已经存在了。

为什么推荐方案二?

React的合成事件已经封装了DOM元素的常用属性,直接访问e.target.name比调用getAttribute更高效,也更符合React组件的开发范式。而且这样你的工具函数不再依赖真实DOM的方法,不管是测试还是实际运行,都更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:00:16