Для начала фокусировка несовершенна.
При использовании 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();
});