如何测试 ngIf,其右操作数与 FormControl 相关?

How to test ngIf, whose right operand is relevant to a FormControl?

我使用 ngIf 在 *.html:

中显示了这样的消息
<input name="name" id="name" formControlName="name" required>
<span *ngIf="name.invalid && (name.dirty || name.touched)" id="message">
   Some messages
</span>

现在我想看看是否生效了。因此,在 *spec.ts 中,我将那个 ngIf 的右操作数设置为 true(通过 "expect" 验证成功),然后使用 debugElement 通过 id 查询它。不幸的是,查询的返回值为空。我认为这意味着上面的跨度尚未创建。

我在设置"name"的值并标记为脏后尝试使用"detectChanges",它仍然不起作用。我尝试过的另一种方法是直接分配该 HTMLInputElement 的值,然后使用 "dispatchEvent",仍然不起作用。

我使用 jasmine 和 karma 来测试我的 Angular 4 应用程序。有人知道如何解决这个问题吗?

谢谢!

ngif 不正确,你必须改变它

*ngIf not ngIf

<span *ngIf="name.invalid && (name.dirty || name.touched)" id="message">
    Some messages
</span>

我就是这样测试的。有些步骤可能不需要,但我全力以赴。

  it('should not show error messages when input is valid', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    const messages = compiled.querySelector('#message');
    expect(messages).toBeFalsy();
  }));

  it('should show error messages when input is invalid', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const component = fixture.componentInstance;
    component.ngOnInit();
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    const input = component.formGroup.controls['name'];
    input.setValue('')
    input.markAsTouched();
    fixture.detectChanges();
    fixture.whenStable().then(() => { 
      const messages = compiled.querySelector('#message');
      expect(messages).toBeTruthy();
    });
  }));