Angular директива юнит тестирования - PullRequest
0 голосов
/ 06 февраля 2020

У меня проблемы с созданием модульного теста для директивы Angular. Проблема в том, что после установки inputEl.value и вызова input.dispatchEvent (new Event ('input')), а затем fixture.detectChanges (), входное значение удаляется и будет пустой строкой (так что в целом я даже не получаю чтобы проверить директиву).

Вот мой код:

@Component({
  template: `
  <form [formGroup]="formGroup">
    <input formControlName="datepicker">
  </form>`
})
class TestComponent implements OnInit {
  formGroup!: FormGroup;

  constructor(private readonly formBuilder: FormBuilder) { }

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.formGroup = this.formBuilder.group({
      datepicker: ['']
    })
  }
}


...
  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  })

it('should add 23:59:59 sec to the initial date', async () => {
    component.ngOnInit();
    fixture.detectChanges();

    const debugEl: HTMLElement = fixture.debugElement.nativeElement;
    const inputEl: HTMLInputElement | null = debugEl.querySelector('input');
    const value = 'test';

    if(inputEl) {
      inputEl.value = value;
      inputEl.dispatchEvent(new Event('input'));
      fixture.detectChanges();
      expect(inputEl.value).toBe(value);
    }
});

Результат: Ошибка: ожидается, что '' будет 'test'.

Что я делаю здесь не так?

...