Угловая единица измерения входного значения

Я читал официальную документацию Angular2 для модульного тестирования (https://angular.io/docs/ts/latest/guide/testing.html), но я борюсь с установкой значения поля ввода компонента так что его отражение в свойстве компонента (связано через ngModel). Экран отлично работает в браузере, но в unit test я не могу установить значение полей.

Я использую код ниже. "fixture" правильно инициализируется, так как другие тесты работают нормально. "comp" - это экземпляр моего компонента, а поле ввода привязано к "user.username" через ngModel.

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

Моя версия Angular2: "@angular/core": "2.0.0"

Ответы

Ответ 1

Входные данные не имеют textContent, только значение. Так expect(field.textContent).toBe('someValue'); бесполезно. Это, вероятно, то, что не удалось. Второе ожидание должно пройти, хотя. Здесь полный тест.

@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() после fixture.detectChanges().

Ответ 2

Просто добавьте

fixture.detectChanges();

fixture.whenStable().then(() => {
  // here your expectation
})

Ответ 3

Используйте ваш whenStable.then/утвержденный в функции whenStable.then так:

component.label = 'blah';
fixture.detectChanges();

fixture.whenStable().then(() => {
    expect(component.label).toBe('blah');
}