我正在尝试单元测试我的按钮是否已聚焦,但我似乎无法让间谍正常工作?
我看到了[这篇文章][1],但它并没有完全帮助。
我错过了一些明显的东西吗?
组件.ts
ngOnInit() {
// autofocus on the cancel button to guard against mistakes
document.getElementById('cancel').focus();
}
焦点一开始就有缺陷。
使用Angular 时,不应使用document
来获取元素。
请改用视图子。
@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();
});
在规范中创建spy
后,ngOnInit()
回想一下,如@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();
});