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

Jest测试React组件:验证blur事件触发指定函数的方法

问题修复方案

你的测试失败核心原因是错误监听了DOM元素的blur原生方法,而非组件的getInput目标函数。以下是两种直接可行的修复方案:

方案一:监听组件实例的getInput方法

由于组件是类组件,可以通过渲染后的容器获取组件实例,对getInput方法做spy监听:

test('search bar focus out triggers getInput', () => {
  const { container } = render(<SearchBar />);
  // 获取SearchBar组件实例
  const searchBarInstance = container.firstChild._internalInstanceHandle.stateNode;
  // 监听getInput方法
  const getInputSpy = jest.spyOn(searchBarInstance, 'getInput');
  
  const input = screen.getByLabelText('Search');
  fireEvent.blur(input);
  
  expect(getInputSpy).toHaveBeenCalled();
  // 清理spy避免影响其他测试
  getInputSpy.mockRestore();
});

方案二:验证localStorage的调用逻辑

getInput的核心作用是将值存入localStorage,直接mock并验证localStorage.setItem的调用更贴合业务逻辑:

test('search bar focus out saves value to localStorage', () => {
  // mock localStorage.setItem方法
  const setItemSpy = jest.spyOn(window.localStorage, 'setItem');
  
  render(<SearchBar />);
  const input = screen.getByLabelText('Search');
  // 先输入测试值
  fireEvent.change(input, { target: { value: 'test query' } });
  fireEvent.blur(input);
  
  expect(setItemSpy).toHaveBeenCalledWith('searchValue', 'test query');
  // 清理spy
  setItemSpy.mockRestore();
});

额外提示

  • 若使用Material-UI的TextField,如果getByLabelText无法定位元素,可改用screen.getByRole('textbox', { name: /search/i })获取底层input。
  • 当前组件中onBlur={this.getInput}未绑定this,虽然当前逻辑没问题,但后续若扩展组件用到this会触发错误,建议改为onBlur={(e) => this.getInput(e)}或在构造函数中提前绑定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:45:41