2017-10-28 114 views
0

我用ngIf显示在*。html的这样一些信息:如何测试其右操作数与FormControl相关的ngIf?

<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查询它。不幸的是,查询的返回值为空。我认为这意味着上面的跨度尚未创建。

我已经尝试使用“detectChanges”后,我设置“名称”的值并将其标记为脏,它仍然无法正常工作。我尝试过的另一种方法是直接指定HTMLInputElement的值,然后使用“dispatchEvent”,但仍然无效。

我利用茉莉花和业力来测试我的Angular 4应用程序。任何人都知道如何解决这个问题?

谢谢!

+0

这是什么'

+0

对不起,这是一个错字... –

回答

0

这是我成功地测试它。有些步骤可能不是必需的,但我把所有的东西都扔在了它上面。

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(); 
    }); 
    })); 
+0

非常感谢你:)我忘了初始化组件。现在它工作了! –

1

ngif是不正确的,你必须改变它

*ngIf not ngIf 

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

对不起,这是一个错字。我改变了它。 –