Angular 2测试:从ngModel获取价值 [英] Angular 2 Testing: Get Value from ngModel

查看:48
本文介绍了Angular 2测试:从ngModel获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个对Angular的 ngModel 属性进行断言的测试.在这一点上,我可以轻松地测试标签.但是,我无法从 ngModel

I'm trying to write a test that asserts on Angular's ngModel attribute. At this point, I can easily test the label. However, I am not able to select the value from ngModel

问题是从 ngModel 获取值的最佳方法是什么?

Question What is the best way to get the value from 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'); 
});

推荐答案

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],
    ...

这篇关于Angular 2测试:从ngModel获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆