如何在Angular组件测试中通过id查找对应的MatInputHarness
解决方法
你不需要遍历数组逐个核对id,Angular Component Harness 原生支持在查询阶段就添加过滤条件,直接匹配指定id的目标元素:
let loader: HarnessLoader = TestbedHarnessEnvironment.loader(fixture); // 传入id过滤条件,一步获取目标input的Harness实例 const targetInput = await loader.getHarness( MatInputHarness.with({ id: '替换为你要查找的input的实际id' }) ); // 后续可以直接对targetInput执行操作、断言 expect(targetInput).toBeTruthy();
MatInputHarness.with() 方法支持的过滤参数除了id之外,还包括placeholder、value、disabled等常用属性,可以满足绝大多数定位场景,不需要先拉取全量Harness再做筛选。
如果你已经提前获取了全量的input Harness数组,也可以用Promise.all并行批量获取所有id再做匹配,性能远高于串行循环await的写法:
const inputs = await loader.getAllHarnesses(MatInputHarness); // 并行获取所有input的id,避免串行异步等待开销 const inputIdList = await Promise.all(inputs.map(item => item.getId())); const targetInput = inputs[inputIdList.findIndex(id => id === '目标id')];
内容的提问来源于stack exchange,提问作者Budda
相关产品推荐
相关产品推荐

