我正在尝试测试按钮单击是否触发了服务方法调用。组件内容(经过清理)看起来像这样
ngOnInit() {
try {
//GET ALL ITEMS
this.service.getAll().pipe(untilDestroyed(this)).subscribe((result) => {
this.list = result;
});
}
catch (ex) {
this._utility.showNotification(ex, 2);
}
}
refresh() {
this.ngOnInit();
}
规格文件如下所示:
it('REFRESH Button should call ngOnInit and getAll', () => {
var spy = spyOn(component, "ngOnInit");
var spyGet = spyOn(component.service, 'getAll').and.returnValue(of([]))
let btnRefresh = fixture.debugElement.query(By.css('.btn-info')).nativeElement
btnRefresh.click()
fixture.whenStable().then(() => {
fixture.detectChanges()
expect(spy).toHaveBeenCalled();
expect(spyGet).toHaveBeenCalled();
})
});
我得到的当前错误如下:
已被调用的预期间谍getAll。
您实际上必须首先将服务注入您的测试中。然后,您监视注入的服务,而不是组件中的内容。示例:
it('should get stores', inject([StoresService], async (service: StoresService) => {
const spy = spyOn(service, 'getStores');
component.ngOnInit();
expect(spy).toHaveBeenCalled();
}));
删除该组件上的间谍已成功完成
it('Refresh button should call getAll', () => {
var spyGet = spyOn(MockApplicationLogService.prototype, 'getAll')
let btnRefresh = fixture.debugElement.query(By.css('.btn-info')).nativeElement
btnRefresh.click()
expect(spyGet).toHaveBeenCalled();
});