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

如何使用Enzyme在React应用测试中模拟div的鼠标悬停事件?

我来帮你搞定用Enzyme测试这个悬停切换下拉菜单的需求~

首先,核心思路是用Enzyme的simulate方法模拟鼠标悬停和离开事件,然后断言下拉菜单SearchMenu的显示/隐藏状态是否符合预期。下面是完整的测试示例,我会一步步解释:

测试步骤说明

  • 初始状态校验:确保组件渲染后,下拉菜单默认是隐藏的
  • 悬停事件测试:模拟鼠标移入父div,校验下拉菜单是否显示
  • 离开事件测试:模拟鼠标移出父div,校验下拉菜单是否隐藏

完整测试代码

import { shallow } from 'enzyme';
import SearchCategory from './SearchCategory'; // 替换成你的组件实际路径
import SearchMenu from './SearchMenu'; // 导入下拉菜单组件

describe('SearchCategory 悬停交互测试', () => {
  let wrapper;
  // Mock 组件需要的 props,避免依赖外部状态
  const mockDispatch = jest.fn();
  const mockSearchSections = [{ id: 1, name: '示例分类' }];

  // 每个测试用例前重新渲染组件,保证状态隔离
  beforeEach(() => {
    wrapper = shallow(
      <SearchCategory 
        searchSections={mockSearchSections} 
        dispatch={mockDispatch} 
      />
    );
  });

  it('初始状态下,下拉菜单应该隐藏', () => {
    expect(wrapper.find(SearchMenu)).toHaveLength(0);
  });

  it('鼠标悬停时,下拉菜单应该显示', () => {
    // 模拟鼠标移入事件(对应组件的 onMouseOver)
    wrapper.find('.search-category').simulate('mouseOver');
    // 断言下拉菜单已渲染
    expect(wrapper.find(SearchMenu)).toHaveLength(1);
    // 可选:校验传递给 SearchMenu 的 props 是否正确
    expect(wrapper.find(SearchMenu).prop('searchSections')).toEqual(mockSearchSections);
  });

  it('鼠标离开时,下拉菜单应该隐藏', () => {
    // 先触发悬停让菜单显示
    wrapper.find('.search-category').simulate('mouseOver');
    expect(wrapper.find(SearchMenu)).toHaveLength(1);

    // 模拟鼠标离开事件(对应组件的 onMouseLeave)
    wrapper.find('.search-category').simulate('mouseLeave');
    // 断言下拉菜单已隐藏
    expect(wrapper.find(SearchMenu)).toHaveLength(0);
  });
});

关键注意点

  • 渲染方式选择:如果只测试当前组件的状态切换,用shallow渲染足够;如果需要测试下拉菜单内部的交互逻辑,可以换成mount渲染。
  • 事件名称:Enzyme的simulate方法支持React合成事件名(比如mouseOver对应onMouseOver),也支持原生DOM事件名(比如mouseover),两种写法都能触发事件。
  • 状态隔离:用beforeEach在每个测试用例前重新渲染组件,避免不同用例之间的状态污染。
  • Props Mock:用jest.fn()模拟dispatch函数,用测试数据模拟searchSections,确保测试不依赖外部Redux或其他状态管理库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:17:37