我似乎无法测试绑定到Angluar2模型的输入框。我对这有点陌生,所以请容忍我。
我有一个非常基本的angular2组件,它包含一个绑定到模型的inputbox。

<form>
    <input  type="text" [(ngModel)]="searchTerm" name="termsearchTerm" (keyup)="search()"  value=""/>
</form>

下面是代码:
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'sc-search',
    templateUrl: 'search.component.html'
})

export class SearchComponent {
    @Input() data: any;
    @Output() onSearchTermChanged = new EventEmitter<string>();
    private searchTerm: string;

    search() {
        this.onSearchTermChanged.emit(this.searchTerm);
    }
}

当运行下面的测试时,保持预期的未定义为等于“john”。
我期待考试通过。
 searchableHierarchyComponentFixture.detectChanges();

    let termInputDbg = searchableHierarchyComponentFixture.debugElement.query(By.css('input[name="termsearchTerm"]'));
    let input = searchableHierarchyComponentFixture.nativeElement.querySelector('input');

    input.value = 'John';

    let evt = document.createEvent('Event');
    evt.initEvent('keyup', true, false);

    termInputDbg.triggerEventHandler('keyup', null);
    input.dispatchEvent(evt);


    tick(50);
    searchableHierarchyComponentFixture.detectChanges();
    searchableHierarchyComponentFixture.whenStable();
    expect(searchableHierarchyComponentFixture.componentInstance.searchTerm).toEqual('John');

最佳答案

所以有几件事:
您需要在创建组件后调用tick。不完全确定,但我认为模型绑定是异步发生的。没有滴答声,测试就会失败。
指令监听input事件,而不是keyup。当input事件发生时,指令将更新绑定。
下面是一个完整的测试(也在Plunker上)

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

@Component({
  selector: 'test',
  template: `
    <form>
      <input type="text" [(ngModel)]="query" name="query" />
    </form>
  `
})
class TestComponent {
  query: string;
}

describe('TestComponent: ngModel', () => {

  let fixture;
  let component;

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

  it('should change the value', fakeAsync(() => {
    let input = fixture.debugElement.query(By.css('input')).nativeElement;

    fixture.detectChanges();
    tick();

    expect(component.query).toBeFalsy();

    input.value = 'Hello World';
    input.dispatchEvent(new Event('input'));
    tick();

    expect(component.query).toBe('Hello World');

  }));
});

也见
当有疑问时,有时最好的例子是source code tests

07-24 19:11
查看更多