【问题标题】:Angular 2 how to test content shown / hidden by *ngIfAngular 2 如何测试 *ngIf 显示/隐藏的内容
【发布时间】: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


    【解决方案1】:

    好的,经过反复试验,我发现如果你在 setTimeout 中调用 fixture.detectChanges(),它会显示 *ngIf DOM

    【讨论】:

    • 您根本不需要setTimeout 电话。如果你手动调用detectChanges,这一切都会同步发生。
    猜你喜欢
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 2017-05-11
    • 1970-01-01
    相关资源
    最近更新 更多