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

ReactJS:如何测试组件内Ref的focus方法调用?

解决React组件中Jest测试Ref的focus调用问题

你的问题核心很明确:之前的测试把refInput作为props传入组件,但组件里是直接使用实例属性this.refInput,两者完全没有关联,导致测试无法命中目标逻辑。下面给你两种可行的解决方案:

方案一:直接给组件实例赋值Mock对象

这种方法最简单直接,因为组件里的setStep方法直接访问this.refInput,我们只需要手动给这个实例属性挂载mock的focus函数即可:

it('setStep() should call focus() on the input', () => {
  // SETUP
  const mockFocus = jest.fn();
  const wrapper = shallow(<Example />);
  // 给组件实例的refInput赋值我们的mock对象
  wrapper.instance().refInput = { focus: mockFocus };
  
  // EXECUTE
  // 调用setStep,传入组件当前的state(和组件里bind的参数保持一致)
  wrapper.instance().setStep(wrapper.instance().state);
  
  // VERIFY
  expect(mockFocus).toHaveBeenCalled();
});

方案二:捕获Ref回调并手动传入Mock对象

如果你想更贴近组件的真实渲染逻辑,可以获取Input组件的ref回调函数,主动调用它来设置this.refInput:

it('setStep() should call focus() on the input', () => {
  // SETUP
  const mockFocus = jest.fn();
  const wrapper = shallow(<Example />);
  
  // 获取Input组件上的ref回调函数
  const inputRefHandler = wrapper.find(Input).prop('ref');
  // 调用回调,传入我们的mock input对象
  inputRefHandler({ focus: mockFocus });
  
  // EXECUTE
  wrapper.instance().setStep(wrapper.instance().state);
  
  // VERIFY
  expect(mockFocus).toHaveBeenCalled();
});

额外注意点

  1. 你测试代码里的myFunction应该是笔误,组件中对应的方法是setStep,测试时要调用正确的方法;
  2. 如果Input是第三方UI组件(比如Ant Design的Input),shallow渲染时它会被当作组件实例处理,但我们的mock对象只需要提供focus方法即可,不影响测试逻辑;
  3. 因为focus是在setState之后同步调用的,不需要等待setState完成,所以无需额外处理异步更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:44:04