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

Angular Material中如何查找嵌套Harness并限定查询作用域到表格行

解决方案

核心原理

  • 所有继承自ComponentHarness的类实例,自带的locatorFor/locatorForAll方法,默认查找范围就是当前Harness对应DOM元素的内部,天然支持作用域限定
  • 你之前的写法错误点有三个:
    1. 拼写错误:MattButtonHarness多写了字母t,正确应为MatButtonHarness
    2. 调用locatorForAll的主体错误:不应该在父级的ProductComponentHarness实例上调用,应该在你要限定范围的MatRowHarness实例上调用
    3. ancestor配置项仅支持传入CSS选择器字符串,不支持直接传入Harness实例,所以之前的配置方式无效

正确实现代码

export class ProductComponentHarness extends ComponentHarness {
  static readonly hostSelector = 'my-selector-component';

  private readonly table = this.locatorFor(MatTableHarness);

  async getRows(): Promise<MatRowHarness[]> {
    const tableResolved = await this.table();
    return tableResolved.getRows();
  }

  async getAllButtonsFromFirstRow(): Promise<MatButtonHarness[]> {
   const firstRow = (await this.getRows())[0];
   // 直接在行实例上调用查找方法,自动限定作用域在当前行内
   const locateButtonsInRow = firstRow.locatorForAll(MatButtonHarness);
   // locatorForAll返回的是查询函数,需要调用后拿到结果
   return locateButtonsInRow();
  }
}

拓展说明

如果后续需要在更复杂的场景下做范围限定,也可以通过获取Harness对应DOM元素的属性做过滤,比如先拿到所有按钮再通过host().matches()方法校验父级元素,但上面的直接在子Harness实例上调用查找方法是Angular Harness设计的标准用法,性能和可维护性都最优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:36:03