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

如何对生成随机ID的变量进行单元测试?(附Angular测试代码)

如何测试带动态ID的Angular链接元素?

你的模板代码如下:

<div *ngIf="primaryLabel" class="po-widget-footer">
    <div class="po-widget-xl" *ngIf="!secondaryLabel">
      <a class="po-widget-action" id="primaryAct[{{ id }}]" (click)="runPrimaryAction($event)">{{ primaryLabel }}</a>
    </div>
</div>

针对动态ID的元素获取,有几种可靠的解决方案:

方案1:利用组件id属性构造选择器

测试时先固定组件的id值(避免随机值干扰),再拼接出可预测的选择器:

it('should have been clicked in primary action', () => {
  spyOn(component.primaryAction, 'emit');
  
  // 固定组件id,确保选择器可精准匹配
  component.id = 'test-fixed-id';
  component.primaryLabel = '确认'; // 满足外层*ngIf显示条件
  component.secondaryLabel = null; // 满足内层*ngIf显示条件
  fixture.detectChanges();

  // 通过组件id拼接目标元素选择器
  const link = nativeElement.querySelector(`#primaryAct[${component.id}]`);

  const eventClick = new Event('click');
  spyOn(eventClick, 'stopPropagation');

  link.dispatchEvent(eventClick);

  expect(component.primaryAction.emit).toHaveBeenCalled();
  expect(eventClick.stopPropagation).toHaveBeenCalled();
});

方案2:通过类选择器直接获取

如果页面中只有这一个po-widget-action类的链接,直接用类选择器更简洁:

const link = nativeElement.querySelector('.po-widget-action');

方案3:组合父元素类缩小范围

当页面存在多个同类别元素时,结合父容器的类精准定位目标元素:

const link = nativeElement.querySelector('.po-widget-xl .po-widget-action');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 03:54:29