简体   繁体   English

茉莉花 - 测试 - 获取内部元素 <ng-template> (角)

[英]Jasmine-Tests - Get elements inside <ng-template> (Angular)

I would like to test HTML elements within a ng-tamplate. 我想在ng-tamplate中测试HTML元素。

<ng-template>
  <button class="create"></button>
</ng-template>

Jasmine Test: 茉莉花测试:

fixture = TestBed.createComponent(SomeComponent);
const htmlElement: HTMLElement = fixture.nativeElement;
// Does not work:
const p = htmlElement.querySelector('.create');

How can I get the html element inside the ng-template? 如何在ng-template中获取html元素? If I place the button outside of the ng-template tag, it works. 如果我将按钮放在ng-template标签之外,它就可以工作。 I think it has something to do with the shadow dom. 我认为它与影子dom有关。

Versions: Jasmine 2.8.0; 版本:Jasmine 2.8.0; Angular 5.2.9 Angular 5.2.9

I forgot to call fixture.detectChanges(); 我忘了打电话给fixture.detectChanges(); . Only when you call this method, the component is rendered fully into the DOM (including shadow-DOM-elements). 只有在调用此方法时,组件才会完全呈现到DOM中(包括shadow-DOM元素)。 The following code works: 以下代码有效:

fixture = TestBed.createComponent(SomeComponent);
fixture.detectChanges();
const htmlElement: HTMLElement = fixture.nativeElement;
const p = htmlElement.querySelector('.create');

See https://angular.io/guide/testing#detectchanges for more details. 有关详细信息,请参阅https://angular.io/guide/testing#detectchanges

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM