关于jasmine:angular2:如何测试页面上是否包含NgBootstrap组件(和内容)?

Angular 2: How to test that an NgBootstrap component (and contents) are on the page?

这个问题在我的测试中不断出现,我正在尝试测试NgBootstrap组件内的元素内容(如模式)。即使Karma浏览器页面上显示的组件很好,测试似乎也无法判断该组件是否存在。

例如,我正在使用NgbModal;它package在<ng-template>中,并通过调用NgModal \\的open方法进行渲染,该方法根据文档通过模板引用变量传递模式内容,并在屏幕上进行渲染时,标记就像:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<ngb-modal-window role="dialog" style="display: block;" tabindex="-1" class="modal fade show">
   
       
 
   
      <h4 _ngcontent-c0="" class="modal-title">Confirm changes</h4>
      <button _ngcontent-c0="" class="close" aria-label="Close" type="button">
        <span _ngcontent-c0="" class="ng-tns-c0-0" aria-hidden="true" title="Close">×</span>
      </button>
   
   
      <p>Save changes?</p>
   
   
     
        <button _ngcontent-c0="" class="btn btn-link mr3" aria-label="Close" type="button">
            <span _ngcontent-c0="" class="ng-tns-c0-0" aria-hidden="true" title="Cancel">Cancel</span>
          </button>
        <button _ngcontent-c0="" class="btn btn-primary btn-raised" title="Save the update">Save changes</button>
     
   
 

   
    </ngb-modal-window>

但是,如果在测试中我尝试fixture.debugElement.query(By.css('ngb-modal-window'))
By.css('#save-modal')(模式中的DIV)均不返回HTML元素。是的,我正在使用fixture.detectChanges()。我只是不知道测试是否仍然不是"看到"该组件(以及如何处理),或者By.css是否无法搜索非标准HTML元素,或者什么。

新信息:当我使用VS Code时,我可以调试测试并在断言上使用断点:

1
2
3
4
tick(); //desperately trying anything, even though nothing async is going on
fixture.detectChanges();
let modalEl = fixture.debugElement.query(By.css('ngb-modal-window'));
expect(modalEl).toBeDefined('defined'); //<===breakpoint here

查看业力浏览器页面时,模态尚未打开;只有当我继续执行代码时,才会弹出模式对话框。那么当我已经调用了detectChanges()时,我还需要做些什么来使视图更新?


模态不是组件的子代。它包含在文档正文中。因此,您可以仅使用文档来查找模态:

1
document.querySelector('ngb-modal-window');

1
document.querySelector('.modal-content');

您可以使用ng-bootstrap测试作为启发: