Angular 2测试:从ngModel获取价值

时间:2017-03-23 17:35:12

标签: angular angular4

我试图编写一个在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'); 
});

1 个答案:

答案 0 :(得分:5)

asyncwhenStable

一起使用
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

fakeAsynctick

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');
}));

Plunker Example

不要忘记导入FormsModule

TestBed.configureTestingModule({
    imports: [FormsModule],
    ...