【问题标题】:How to test a dropdown-toggle operation in angular 2 testing?如何在 Angular 2 测试中测试下拉切换操作?
【发布时间】:2018-03-24 14:06:01
【问题描述】:

我正在尝试测试下拉切换功能。但我无法让它发挥作用。我还将BsDropdownModule 导入到规范文件中。 注意:我使用的是 ngx-bootstrap。

这是我尝试过的:

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*/
});

任何人都可以提出正确的方法吗?

【问题讨论】:

  • 嗨,你能告诉我你是如何在你的规范中导入 BsDropdownModule 的吗?当我这样做时,它给了我一堆静态注入器错误。我尝试了您的解决方案,但我遇到了同样的问题,即使单击按钮后,dom 中也不存在 ul。
  • 您是否尝试过添加 FormsModule?您是否收到 BsDropdownModule 的注入器错误?

标签: angular unit-testing typescript karma-jasmine ngx-bootstrap


【解决方案1】:

我已经设法解决了这个问题。这只是一个愚蠢的错误。列表中的数据由异步进程填充。所以我应该在单击下拉按钮后使用fakeAsynctick()。在将数据填充到列表中之前更新了视图。这导致了问题。这是固定的代码:

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]);
}));

【讨论】:

  • 谢谢,帮助了我。不确定这是否是一个愚蠢的错误——我认为知道并记住何时必须使用 fakeAsync / tick 并不容易。
  • 我看不出你的期望,你不需要对这个测试有期望吗?
  • @Girum 一定有期望,我只是没有包括它,因为它与解释我的问题无关。
  • 谢谢 Sanju,知道了,不过你的例子很棒。
  • 嗨,@Sanju 在这种情况下我可以使用异步等待吗,点击下拉菜单后?像这样 await SleepForASecond(0) 这是我在 SleepForASecond 中的代码 static sleep(ms) { return new Promise(resolve =&gt; setTimeout(resolve, ms)); } static async SleepForASecond(ms) { await this.sleep(ms); }
猜你喜欢
  • 2017-07-23
  • 2011-12-02
  • 2017-01-13
  • 2017-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
相关资源
最近更新 更多