Угловой - модульное тестирование с упором на кнопку - PullRequest
0 голосов
/ 30 августа 2018

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

Я видел [этот пост] [1], но это не помогло полностью.

Я что-то упускаю из виду?

component.ts

ngOnInit() {
    // autofocus on the cancel button to guard against mistakes
    document.getElementById('cancel').focus();
  }

Ответы [ 2 ]

0 голосов
/ 30 августа 2018

Для начала фокусировка несовершенна.

При использовании Angular не следует использовать document для извлечения ваших элементов.

Используйте взамен viewChild.

@ViewChild('cancel') cancelButton: ElementRef<HtmlButtonElement>;
ngAfterViewInit() {
  this.cancelButton.nativeElement.focus();
}

Теперь ваш тест выглядит так

it('should focus cancel button', () => {
  spyOn(component.cancelButton.nativeElement, 'focus');
  component.ngAfterViewInit();
  expect(component.cancelButton.nativeElement.focus).toHaveBeenCalledWith();
});

РЕДАКТИРОВАТЬ Если вы все еще хотите использовать свой путь, рассмотрите возможность использования By.css():

it('should autofocus on cancel button on init', () => {
  const cancelButton = fixture.debugElement.query(By.css('#cancel'));
  spyOn(cancelButton, 'focus');
  component.ngOnInit();
  expect(cancelButton.focus).toHaveBeenCalled();
});
0 голосов
/ 30 августа 2018

Напомним ngOnInit() после того, как ваш spy был создан в вашей спецификации, как указано @ trichietrichie

Кроме того, используйте fixture вместо того, чтобы полагаться на document для извлечения html-элементов.

beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ ConfirmationComponent ],
      providers: [ MessageService]
    });

    fixture = TestBed.createComponent(ConfirmationComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();    
    component.ngOnInit();
  });

  it('should autofocus on cancel button on init', () => {
    const cancelButton = fixture.debugElement.query(By.css('#cancel'));
    spyOn(cancelButton.nativeElement, 'focus'); // create spy here   
    component.ngOnInit();
    expect(cancelButton.focus).toHaveBeenCalled();
  });
...