我试图编写一个在Angular的ngModel
属性上断言的测试。此时,我可以轻松测试标签。但是,我无法从ngModel
问题从
ngModel
获取价值的最佳方式是什么?
HTML:
<div name="customerName">
<label>Customer Name: </label>
<div>
<input type="text" class="form-control" [ngModel]="customer.name" asInline disabled />
</div>
</div>
测试
it('bindings', () => {
fixture = TestBed.createComponent(CustomerComponent);
fixture.detectChanges();
// this works
expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] label').textContent).toEqual('Customer Name: ');
// this assert fails
expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] div input').value).toEqual('Bobby Tables');
});
答案 0 :(得分:5)
将async
与whenStable
it('should recognize a timepicker', async(() => {
fixture = TestBed.createComponent(ExampleComponent);
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] label').textContent).toEqual('Customer Name: ');
expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] div input').value).toEqual('Bobby Tables');
});
}));
<强> Plunker Example 强>
或fakeAsync
与tick
:
it('should recognize a timepicker', fakeAsync(() => {
fixture = TestBed.createComponent(ExampleComponent);
fixture.detectChanges();
tick();
expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] label').textContent).toEqual('Customer Name: ');
expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] div input').value).toEqual('Bobby Tables');
}));
不要忘记导入FormsModule
:
TestBed.configureTestingModule({
imports: [FormsModule],
...