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

如何用Jest测试React组件中的箭头函数调用?新手报错排查

解决Jest/Enzyme测试React Button组件时的"Cannot read property 'onIncrement' of undefined"错误

嘿,我来帮你排查这个问题~你遇到的错误主要来自两个小细节问题,咱们一步步来修复:

问题1:组件Props传递方式错误

你在渲染Button组件时写了{...{props}},这相当于把一个嵌套的{ props: { onIncrement, counter } }对象传给了组件,而不是直接展开你定义的props对象。这就导致组件内部拿到的props结构变了,原本要访问的props.onIncrement变成了props.props.onIncrement,自然就会抛出"undefined"的错误。

问题2:断言对象选错了

你现在写的expect(button).toHaveBeenCalledWith('pc')是错误的——button是组件的shallow渲染实例,并不是你要验证的mock函数。你需要断言的是你创建的onIncrement这个jest mock函数,以此验证按钮点击后它是否被正确调用。


修复后的测试代码

describe("Name of the group", () => { 
  const counter = 'pc'; 
  const onIncrement = jest.fn(); 
  const props = { onIncrement, counter }; 
  it("should trigger onIncrement with correct counter when clicked ", () => { 
    // 修复:直接展开props对象,而非嵌套的{props}结构
    const button = shallow(<Button {...props}>Increment</Button>); 
    button.find(".increment").simulate("click"); 
    // 修复:断言目标改为mock函数onIncrement
    expect(onIncrement).toHaveBeenCalledWith('pc'); 
  }); 
});

关键修改点说明

  • 把{...{props}}改成{...props}:这样才能正确把onIncrement和counter作为独立props传递给Button组件,组件内部就能直接通过props.onIncrement和props.counter访问到它们。
  • 把expect(button)改成expect(onIncrement):我们要验证的是按钮点击后,onIncrement这个mock函数是否被触发,并且调用参数是预期的'pc'。

这样修改后,你的测试应该就能正常运行,不会再出现undefined的错误啦~

内容的提问来源于stack exchange,提问作者Syed Danish Ali Jr.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:40:31