组件是
https://github.com/valor-software/ngx-bootstrap下拉列表.
在模板中我有这个:
<span dropdown placement="bottom right"> <a id="droplist-label" href="javascript:void(0)" dropdownToggle> <span>{{conf.title}}</span> </a> <ul class="dropdown-menu pull-right" *dropdownMenu> <li *ngFor="let item of items"> <a class="dropdown-item" (click)="listClick(item.value)" href="javascript:void(0)">{{item.label}}</a> </li> </ul> </span>
致电点击:
let droplist = fixture.debugElement.query(By.css('#droplist-label')).nativeElement; droplist.click();
不起作用 – 如果我试图寻找下拉菜单,它是空的:
it('should test if droplist has title',async(() => { fixture.detectChanges(); let droplist = fixture.debugElement.query(By.css('#droplist-label')).nativeElement; droplist.click(); fixture.whenStable().then(() => { let droplistOptions = fixture.debugElement.queryAll(By.css('.dropdown-item')); expect(droplistOptions.length).toBeGreaterThan(0); }); }));
该指令似乎有一个用于click事件的hostlistener – 如何触发它以便ul可用?
解决方法
我终于使用
fakeAsync()解决了同样的pb:
it('should render submenus',fakeAsync(() => { fixture.detectChanges(); // update the view // trig submenus @R_403_126@ let toggleButtons = fixture.debugElement.nativeElement.querySelectorAll('[dropdownToggle]'); toggleButtons.forEach(b => b.click()); tick(); // wait for async tasks to end fixture.detectChanges(); // update the view // then count how many items you got for each submenus. let droplistOptions1= fixture.debugElement.nativeElement.querySelectorAll('#first-ul > li') let droplistOptions2= fixture.debugElement.nativeElement.querySelectorAll('#second-ul > li') let droplistOptions3= fixture.debugElement.nativeElement.querySelectorAll('#third-ul > li') expect(droplistOptions1.length).toEqual(3); expect(droplistOptions2.length).toEqual(5); expect(droplistOptions3.length).toEqual(2); }));
但我确信可以使用async()来实现:我猜你在初始尝试时只在fixture.whenStable()开始时错过了fixture.detectChanges().然后(…).
另外,请记住将BsDropdownModule导入测试平台:
import { BsDropdownModule} from 'ngx-bootstrap/dropdown'; ... TestBed.configureTestingModule({ imports: [ BsDropdownModule.forRoot(),],... });