Fab*_*ian 6 html testing jasmine karma-jasmine angular
我想在 ng-tamplate 中测试 HTML 元素。
<ng-template>
<button class="create"></button>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
茉莉花测试:
fixture = TestBed.createComponent(SomeComponent);
const htmlElement: HTMLElement = fixture.nativeElement;
// Does not work:
const p = htmlElement.querySelector('.create');
Run Code Online (Sandbox Code Playgroud)
如何在 ng-template 中获取 html 元素?如果我将按钮放在 ng-template 标签之外,它就可以工作。我认为这与影子dom有关。
版本:茉莉花 2.8.0;角 5.2.9
我忘了打电话fixture.detectChanges();
。仅当您调用此方法时,组件才会完全渲染到 DOM 中(包括 Shadow-DOM-elements)。以下代码有效:
fixture = TestBed.createComponent(SomeComponent);
fixture.detectChanges();
const htmlElement: HTMLElement = fixture.nativeElement;
const p = htmlElement.querySelector('.create');
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅https://angular.io/guide/testing#detectchanges 。