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

AgGrid选择器返回null,Karma-Jasmine单元测试无法获取行元素

Ag-Grid单元测试无法选中表格行元素的问题解决

问题场景

我有一个包含Ag-Grid的组件:

<app-my-component>
  <ag-grid-angular
    [gridOptions]="gridOptions"
    (gridReady)="setGridReady()">
  </ag-grid-angular>
</app-my-component>

单元测试中,验证表格渲染的测试能正常通过:

it('Should render data table', async(() => { 

  // Wait for ag grid to render rows
  fixture.detectChanges();

  fixture.whenStable().then(() => {
    const agGrid = element.query(By.css('ag-grid-angular'));
    expect(agGrid).toBeTruthy();
  });

}));

但测试表格行数时,用CSS选择器.my-custom-class或.ag-cell-value始终无法选中元素,测试失败:

it('Should display all three rows from mock data', async(() => {

  // Wait for ag grid to render rows
  fixture.detectChanges();

  fixture.whenStable().then(() => {
    let rows = element.queryAll(By.css('.my-custom-class'));
    expect(rows.length).toBe(3);
  });

}));

奇怪的是,页面上明明能看到表格和3行数据,但直接在控制台执行选择器返回null;只有右键检查元素展开DOM后,选择器才能正常返回结果。

原因分析

Ag-Grid的表格内容是渲染在Shadow DOM中的,这是一种DOM封装技术,默认情况下普通CSS选择器和DOM查询无法穿透Shadow DOM访问内部元素。而当你在开发者工具中展开Ag-Grid元素时,浏览器会强制暴露Shadow DOM内容,此时选择器才能找到对应元素。

解决方案

方法一:使用Ag-Grid官方API(推荐)

直接通过Ag-Grid提供的API获取行数,避免依赖DOM结构,测试更稳定:

it('Should display all three rows from mock data', async(() => {
  fixture.detectChanges();

  fixture.whenStable().then(() => {
    // 获取Ag-Grid组件实例
    const agGridComp = element.query(By.css('ag-grid-angular')).componentInstance;
    
    // 监听数据首次渲染完成事件
    agGridComp.api.addEventListener('firstDataRendered', () => {
      // 获取当前显示的行数
      const displayedRowCount = agGridComp.api.getDisplayedRowCount();
      // 或者获取总数据行数(包含未显示的)
      // const totalRowCount = agGridComp.api.getModel().getRowCount();
      expect(displayedRowCount).toBe(3);
    });
  });
}));

方法二:穿透Shadow DOM查询元素(不推荐)

如果必须通过DOM元素验证,可以直接访问Shadow DOM内部进行查询:

it('Should display all three rows from mock data', async(() => {
  fixture.detectChanges();

  fixture.whenStable().then(() => {
    const agGridElement = element.query(By.css('ag-grid-angular')).nativeElement;
    // 访问Shadow Root
    const shadowRoot = agGridElement.shadowRoot;
    // 在Shadow DOM内部查找元素
    const rows = shadowRoot.querySelectorAll('.my-custom-class');
    expect(rows.length).toBe(3);
  });
}));

注意:方法二依赖Ag-Grid的DOM结构,版本更新可能导致选择器失效,优先使用方法一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:01:11