【发布时间】:2017-11-07 13:53:02
【问题描述】:
我在单元测试中遇到了一些困难,该测试正在读取一些正在使用 *ngIf 从 DOM 中添加/删除的 html。
这是 DOM:
<div class="detailacc" (click)="showDet()">
<i class="fa" [class.fa-caret-right]="!showHideDet " [class.fa-caret-down]="showHideDet " aria-hidden="true"></i>
<h4>Expandable</h4>
</div>
<div *ngIf="showHideDet">
<p class="detailHeader">Details header</p>
</div>
这是在第一个 div 的点击事件上调用的组件函数:
private showDet() {
console.log('show called');
this.showHideDet = !this.showHideDet;
}
最后是规范:
it('should show the header when the expandable elem is clicked', async(() =>
{
const fixture = TestBed.createComponent(DetailsComponent);
const compiled = fixture.debugElement.nativeElement;
let detPresent: boolean = false;
for (let node of compiled.querySelectorAll('.detailacc')) {
node.click();
}
setTimeout(() => {
console.log(compiled.querySelectorAll('.detailHeader'));
for (let node of compiled.querySelectorAll('.detailHeader')) {
if (node.textContent === 'Details header') {
detPresent = true;
break;
}
}
expect(detPresent).toBeFalsy();
}, 0);
}));
如您所见,我已经封装了用于搜索仅当 setTimeout 中的 *ngIf 为 true 时才显示的那些 DOM 元素的代码,如 How to check whether ngIf has taken effect 中所示,但我仍然没有得到任何东西。
此外,如果您想知道是否在该测试中调用了单击,这是因为组件函数中的 console.log 会显示在 Karma 控制台中。 setTimeout 内的console.log 显示了一个NodeList(0),基本上没有找到具有类.detailHeader 的节点。
【问题讨论】:
标签: angular unit-testing jasmine karma-runner