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

使用Jest和Enzyme测试AgGridWrapper组件的onCellClicked事件

Testing the onCellClicked Event in Your AgGridWrapper Component

嘿,先帮你修正下组件里的几个语法小问题——原代码里onCellClicked的绑定写法有误,render方法的标签也没闭合,而且setDataValue调用时缺少字段和明确的新值,先调整成可运行的版本,这样测试才有基础:

class AgGridWrapper extends React.Component { 
  // 用类属性箭头函数自动绑定this,避免手动bind的麻烦
  onCellClicked = (event) => { 
    // 这里补充字段名和具体值,示例用'targetField'和'newUpdatedValue'
    event.setDataValue('targetField', 'newUpdatedValue'); 
  }

  render() { 
    return (
      <AgGridReact 
        onCellClicked={this.onCellClicked} 
      />
    ); 
  } 
}

接下来,基于你已经在用的Enzyme Shallow渲染,我来一步步指导你完成onCellClicked事件的测试:

测试准备(假设用Jest + Enzyme)

首先确保你已经安装了必要的依赖:jest、enzyme、enzyme-adapter-react-xx(对应你的React版本),并配置好了Enzyme适配器。

具体测试步骤

1. 导入依赖与组件

先导入测试所需的工具和你的组件:

import React from 'react';
import { shallow } from 'enzyme';
import AgGridWrapper from './AgGridWrapper';
import AgGridReact from 'ag-grid-react';

2. 编写测试用例

我们的核心目标是验证:当AgGridReact触发onCellClicked事件时,你的组件会正确调用event.setDataValue方法。具体代码如下:

describe('AgGridWrapper', () => {
  it('triggers event.setDataValue when a cell is clicked', () => {
    // 1. 浅渲染AgGridWrapper组件
    const wrapper = shallow(<AgGridWrapper />);

    // 2. 获取传递给AgGridReact的onCellClicked回调函数
    // 两种方式可选:
    // 方式一:通过find获取AgGridReact组件,然后取出prop
    const handleCellClick = wrapper.find(AgGridReact).prop('onCellClicked');
    // 方式二:Mock AgGridReact后取mock调用的参数(如果不想依赖组件渲染细节,推荐这种)
    // jest.mock('ag-grid-react', () => ({ AgGridReact: jest.fn(() => null) }));
    // const handleCellClick = AgGridReact.mock.calls[0][0].onCellClicked;

    // 3. 创建模拟的event对象,用jest.fn()跟踪setDataValue的调用
    const mockEvent = {
      setDataValue: jest.fn()
    };

    // 4. 手动触发回调函数,传入模拟的event
    handleCellClick(mockEvent);

    // 5. 验证setDataValue是否被正确调用
    expect(mockEvent.setDataValue).toHaveBeenCalled();
    // 如果你的业务逻辑是给特定字段设置固定值,还可以验证调用参数:
    expect(mockEvent.setDataValue).toHaveBeenCalledWith('targetField', 'newUpdatedValue');
  });
});

3. 补充说明

  • 如果你的onCellClicked逻辑依赖组件的props或state,记得在渲染AgGridWrapper时传入对应的测试数据,比如shallow(<AgGridWrapper someProp={testValue} />)。
  • Shallow渲染的优势是不会深入渲染子组件(这里就是AgGridReact),所以我们只需要关注组件之间的props传递和回调逻辑,不需要关心AgGridReact内部的实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:43:11