我一直在阅读单元测试的官方Angular2文档(https://angular.io/docs/ts/latest/guide/testing.html),但我很难设置组件的输入字段值,以便其反映在组件属性中(通过ngModel绑定).屏幕在浏览器中运行良好,但在单元测试中,我似乎无法设置字段值.

我使用下面的代码.当其他测试正常运行时,"fixture"已正确初始化."comp"是我的组件的实例,输入字段通过ngModel绑定到"user.username".

it('should update model...', async(() => {
    let field: HTMLInputElement = fixture.debugElement.query(By.css('#user')).nativeElement;
    field.value = 'someValue'
    field.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    expect(field.textContent).toBe('someValue');
    expect(comp.user.username).toBe('someValue');
  }));

我的版本"天使2:"@angular/core": "2.0.0""

推荐答案

输入没有文本内容,只有一个值.所以expect(field.textContent).toBe('someValue');是没用的.这可能就是失败的地方.第二个期望应该会过go .这是一个完整的测试.

@Component({
  template: `<input type="text" [(ngModel)]="user.username"/>`
})
class TestComponent {
  user = { username: 'peeskillet' };
}

describe('component: TestComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [ TestComponent ]
    });
  });

  it('should be ok', async(() => {
    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      let input = fixture.debugElement.query(By.css('input'));
      let el = input.nativeElement;

      expect(el.value).toBe('peeskillet');

      el.value = 'someValue';
      el.dispatchEvent(new Event('input'));

      expect(fixture.componentInstance.user.username).toBe('someValue');
    });
  }));
});

重要的是前fixture.whenStable()名.发生的表单有一些异步设置,所以我们需要在执行fixture.detectChanges()之后等待完成.如果您使用fakeAsync()而不是async(),那么您可以在fixture.detectChanges()之后直接呼叫tick().

Angular相关问答推荐

将Angular Metal的芯片组件集成到我的表单中时出错

如何避免使用CSS动画制作的幻灯片中闪烁?

间歇性不正确的SSR重定向(server. ts级别的请求和响应不匹配)

P-DropDown不会使用react 式表单手动设置Value

Angular CLI 与 Angular 版本不兼容

使用 Angular 类构造函数来获取依赖项

如何在 Angular RxJS 中替换订阅中的 subscrib?

在生产模式下使用带Angular 的 livekit

Angular combinelatest使用没有初始值的主题

Angular 2 二传手与 ngOnChanges

为什么 Angular2 routerLinkActive 将活动类设置为多个链接?

Angular 2 通过 [class.className] 绑定添加多个类

在 Angular 4 中播放声音

Angular 2 - 全局 CSS 文件

Failed to execute 'setAttribute' on 'Element': ']' is not a valid attribute name

得到了预期表达式的插值 ({{}})

Angular 中 polyfills.ts 文件有什么用

Angular:找不到不同的支持对象[object Object]

'Observable' 类型上不存在属性 'filter'

为什么 ngOnInit 被调用两次?