Reputation: 2293
I'm trying to test that a button click triggers a service method call. The component content (a bit cleaned) looks like this
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();
}
and the spec file looks like this:
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();
})
});
The current error what I get is the following:
Expected spy getAll to have been called.
Upvotes: 1
Views: 181
Reputation: 2293
removing the spy on the component did the trick
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();
});
Upvotes: 1
Reputation: 12970
You actually have to inject the service into your test first. Then, you spy on your injected services rather than what is in your component. Example:
it('should get stores', inject([StoresService], async (service: StoresService) => {
const spy = spyOn(service, 'getStores');
component.ngOnInit();
expect(spy).toHaveBeenCalled();
}));
Reference: https://angular.io/guide/testing
Upvotes: 1