如何对生成随机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
相关产品推荐
相关产品推荐

