使用 phantomjs 的 Karma 测试因 ngIf 而失败

Karma test with phantomjs fails with ngIf

我有一个 angular-cli 项目。

我要测试的 html 看起来像这样:

<div *ngIf="!isMobile" class="shop-description">
  {{ description }}
</div>
<div class="shop-link">
  <span>
    {{ link}}
  </span>
</div>

测试看起来像这样:

  beforeEach(() => {
    fixture = TestBed.createComponent(ShopItemComponent);
    component = fixture.componentInstance;
    component.shop = ShopServiceMock.shops[0];
    component.isMobile = false;
    fixture.detectChanges();
  });
  it('should have a title', () => {
        fixture.detectChanges();
        const el = fixture.debugElement.nativeElement;
        expect(el.querySelector('div.shop-title>span').innerText).toContain('test');
    });

  it('should have a description', () => {
        fixture.detectChanges();
        const el = fixture.debugElement.nativeElement;
        expect(el.querySelector('div.shop-description').innerText).toContain('love');
    });

使用命令 'ng test' 一切都通过了,没问题。

With 'npm 运行 test:phantomjs -- --code-coverage' 对 title 元素的第一个测试通过但对 description 的测试失败与:

TypeError: null is not an object (evaluating 'el.querySelector('div.shop-description').innerText')

我将 component.isMobile = false; 移到 it('should... 中并消除了错误。

我不确定为什么会这样,但如果有人有解释,我愿意提供想法。

如果您有一个 *ngIf 将元素设置为不存在。 这就是为什么在查找之前应先将 isMobile 设置为 false 的原因。