首页 > 解决方案 > DebugElement.query 不适用于在规范中动态添加到 dom 的元素

问题描述

我有一个应用程序使用 ngx-bootstrap 在鼠标悬停时显示工具提示。我想测试动态添加的内容是否正确显示。为了做到这一点,我有一个看起来像这样的测试:

it(shows the right tooltip', fakeAsync(() => { 
  fixture.debugElement.query(By.directive(TooltipDirective))
         .triggerEventHandler('mouseover', null);
  tick();
  fixture.detectChanges();

  expect(fixture.debugElement.query(By.css('.tooltip-inner')).nativeElement)
        .toBe('the tooltip text');
}

这会导致错误指示fixture.debugElement.query(By.css('.tooltip-inner')):“无法读取 null 的属性‘nativeElement’”

如果我打印出fixture.debugElement.nativeElement我得到这个的内容:

<div id="root1" ng-version="5.2.9">
  <my-component>
    <div ng-reflect-tooltip="the tooltip text">
      <img src="images/test.png">
    </div>
    <bs-tooltip-container role="tooltip" class="tooltip in tooltip-right">
      <div class="tooltip-arrow arrow"></div>
      <div class="tooltip-inner">the tooltip text</div>
    </bs-tooltip-container>
  <my-component>
</div>

重要的一点是 html 存在 - 它只是无法通过DebugElement.query.

我目前获得规范通过的解决方案是将期望更改为:

expect(fixture.debugElement.nativeElement.textContent.trim())
      .toBe('the tooltip text');

这是可行的,但如果我遇到具有多个工具提示的类似情况(例如),它就会崩溃。有没有人能够以更好的方式处理这个问题?我没有正确设置这个规范吗?

标签: testingjasmine

解决方案


推荐阅读