如何在角度2测试中测试下拉式切换操作?
问题描述:
我想测试下拉切换功能。但我无法实现它的工作。我还将BsDropdownModule
导入了spec文件。 注意:我正在使用ngx-bootstrap。如何在角度2测试中测试下拉式切换操作?
这里是我的尝试:
HTML:
<div class="btnBox" dropdown placement="bottom right">
<button class="btnIcon dropdown-toggle" dropdownToggle>
</button>
<ul class="btnOptionBox dropdown-menu dropdown-menu-right" *dropdownMenu>
<li class="iconBtn" (click)="someFun()" type="button"><span>Edit</span></li>
<li class="iconBtn" (click)="someFun1()" type="button"><span>Delete</span></li>
</ul>
</div>
测试规格:
it("Should show options when toggle option is clicked",() => {
fixture.detectChanges();
let toggleButton = fixture.debugElement.queryAll(By.css('[dropdownToggle]'));
toggleButton[0].nativeElement.click();
fixture.detectChanges();
/*Unable to access li tag directly. That's why I have used it's parent*/
let list = fixture.debugElement.queryAll(By.css('div.ellipsisBox'));
console.log(list[0]); /*Shows the list in the children array*/
console.log(list[0].children); /*Doesn't show the list*/
});
任何人都可以提出这样做的正确方法?
答
我设法解决了这个问题。这只是一个愚蠢的错误。列表中的数据由异步过程填充。所以我点击下拉按钮后应该使用fakeAsync
和tick()
。视图在数据填充到列表之前已更新。这导致了这个问题。以下是固定代码:
it("Should show options when toggle option is clicked",fakeAsync(() => {
fixture.detectChanges();
let toggleButton = fixture.debugElement.queryAll(By.css('[dropdownToggle]'));
toggleButton[0].nativeElement.click();
tick();
fixture.detectChanges();
let list = fixture.debugElement.queryAll(By.css('ul.btnOptionBox'));
console.log(list[0]);
}));