即使手动触发更改检测,ngif 标记元素有时也会返回 null

问题描述

我的测试有时会失败,因为在测试中查询时元素不存在。根据我的理解,这不应该发生,因为在查询元素之前,更改检测是由 fixture.detectChanges() 触发的。因此,理论上应该在更改检测期间检查 ngIf 指令,并且在通过测试进行检查时,应该已经完成​​检查。然而,有时情况并非如此。

这种情况下的错误输出是:Type Error: Cannot read property 'nativeElement' of null

测试

it('when blue pen should be clickable',() => {
                // any variable modification
                const openInputSampleSpy = spyOn(component,'openInputSample');

                fixture.detectChanges();
                const bluePen = componentElement.query(By.css('.pen-blue')).nativeElement;
                bluePen.click();

                expect(openInputSampleSpy).toHaveBeenCalledTimes(1);
});

HTML

<button (click)="openInputSample()"
                *ngIf="isBluePenVisible"
                class="pen-blue right-button" [@fadeInOut]>
</button>

解决方法

这很奇怪。尝试像这样明确表示:

it('when blue pen should be clickable',() => {
                // any variable modification
                const openInputSampleSpy = spyOn(component,'openInputSample');

                fixture.detectChanges();
                componentElement.isBluePenVisible = true; // add these 2 lines
                fixture.detectChanges();
                const bluePen = componentElement.query(By.css('.pen-blue')).nativeElement;
                bluePen.click();

                expect(openInputSampleSpy).toHaveBeenCalledTimes(1);
});