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

使用Karma测试Angular MatTable时无法正确填充数据行问题咨询

问题根因&修复方案

1. MatSort赋值时机错误

你在构造函数中给dataSourceRole.sort赋值,但是@ViewChild(MatSort)获取的元素要等视图初始化完成后才会实例化,构造函数执行时sort还是undefined,会导致MatTable数据源配置异常,表格无法正常渲染数据。
修复方式:
给组件实现AfterViewInit接口,把排序赋值逻辑移到ngAfterViewInit钩子中:

// 先导入AfterViewInit
import {Component, OnDestroy, OnInit, ViewChild, AfterViewInit} from '@angular/core';

export class RolesComponent implements OnInit, OnDestroy, AfterViewInit {
  // 原有代码不变,删除构造函数里的this.dataSourceRole.sort = this.sort;语句
  ngAfterViewInit(): void {
    this.dataSourceRole.sort = this.sort;
  }
}

2. 模板标签闭合错误

你HTML模板中created列的表头标签没有正确闭合,错误写法是<th mat-header-cell *matHeaderCellDef>Created<th>,会导致表格DOM结构异常,Harness无法正确识别行数据:
修复方式:
把闭合标签改成</th>:

<ng-container matColumnDef="created">
  <th mat-header-cell *matHeaderCellDef>Created</th>
  <td mat-cell *matCellDef="let dto">{{dto.created | date:'dd/MM/yyyy HH:mm'}}</td>
</ng-container>

3. 测试用例单元格取值方法错误

getCellTextByIndex方法接收的参数是列的索引序号,你传入{columnName: 'ID'}不会生效,且你用的是表头显示文本ID作为列名,实际列定义matColumnDef的值是id,应该用getCellTextByColumnName方法取值。
同时你在推送数据后需要等待异步任务执行完成再检测变更:
修复后的测试用例代码:

it('should display the rows when data is present', async () => {
  let roles: RoleDto[] = [
    {roleId: 'ADMIN', description: 'Admin role', created: new Date(), creator: 0, modified: new Date(), modifier: 0},
    {roleId: 'USER', description: 'User role', created: new Date(), creator: 0, modified: new Date(), modifier: 0},
    {roleId: 'READER', description: 'Reader role', created: new Date(), creator: 0, modified: new Date(), modifier: 0},
  ];
  returnedRoles.next(roles);
  // 等待异步订阅执行完成
  await fixture.whenStable();
  fixture.detectChanges();

  let tableHarness = await loader.getHarness(MatTableHarness);
  let rows = await tableHarness.getRows();
  expect(rows.length).toBe(roles.length);
  for (let i = 0; i < rows.length; i++) {
    const text = await rows[i].getCellTextByColumnName('id');
    expect(text).toContain(roles[i].roleId);
  }
});

做完以上修改测试即可正常运行。

内容的提问来源于stack exchange,提问作者usr-local-ΕΨΗΕΛΩΝ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:54:05