Как провести модульное тестирование углового @Output - PullRequest
0 голосов
/ 14 декабря 2018

Проблема из отчета о покрытии: enter image description here

У меня есть этот код внутри component.ts

export class TimelinePlotComponent implements OnInit, OnChanges, OnDestroy {

form: FormGroup;
@Output() onchange: EventEmitter<any> = new EventEmitter<any>();

constructor() {}

initForm() {
    this.form = new FormGroup({
      timeRange: new FormControl(this.time_range_options_active, []),
      metric: new FormControl(this.metric_options_active, []),
      groupBy: new FormControl(this.group_by_options_active, []),
    });

    // How to unit test this part of the code
    this.form.valueChanges.subscribe( res => {
      console.log('form-changed');
      this.onchange.emit(res);
    });
  }

}

component.spec.ts

  fit('should listen for form changes', async() => {
    component.form.controls['groupBy'].setValue('color');
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      // your expectations.
      expect(component.form.valid).toBeTruthy();
      component.onchange.subscribe( res => {
        console.log('res: ', res);
      });

    });
  });

ошибка: ничего не происходит, я не знаю, как выполнить модульное тестирование формы, которая запускает генератор выходных событий.

Как видите, это не работает,Любая помощь о том, как модульный тест изменения формы?

1 Ответ

0 голосов
/ 14 декабря 2018

Я не думаю, что вам вообще нужен whenStable, также async не нужен.Вы должны использовать detectChanges(), чтобы активировать обнаружение изменений.Но это должно быть сделано только перед фактическим запуском, чтобы вызвать хук ngOnInit (и друзей).

Также используйте spy, чтобы убедиться, что вывод был вызван:

fit('should listen for form changes', () => {
   spyOn(component.onchange, 'emit');
   fixture.detectChanges();

   component.form.controls['groupBy'].setValue('color');

   expect(component.form.valid).toBeTruthy();
   expect(component.onchange.emit).toHaveBeenCalled();
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...