我正在尝试对我的按钮是否已聚焦进行单元测试,但我似乎无法让 spy 正常工作?
我看到了[这篇文章][1],但它并没有完全帮助。
我是否漏掉了一些明显的东西?
component.ts
ngOnInit() {
// autofocus on the cancel button to guard against mistakes
document.getElementById('cancel').focus();
}
最佳答案
焦点从一开始就存在缺陷。
使用 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();
});
关于javascript - Angular - 以按钮为中心的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093496/