The focus is flawed to start with.
When using Angular, you should not use document to fetch your elements.
Use a viewChild instead.
@ViewChild('cancel') cancelButton: ElementRef<HtmlButtonElement>;
ngAfterViewInit() {
this.cancelButton.nativeElement.focus();
}
Now your test looks like this
it('should focus cancel button', () => {
spyOn(component.cancelButton.nativeElement, 'focus');
component.ngAfterViewInit();
expect(component.cancelButton.nativeElement.focus).toHaveBeenCalledWith();
});
EDIT If you still want to use your way, consider using 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();
});