In my component class, my method, getUsers() uses a service called getData(). In my unit test I would like to test if my method is successfully calling getData(). So I wrote a simple test doing so, but I think I am missing something. In my test, I inject the service, create a fakeasync of that service. From there, I spyon my service and the method getData. Then I preform my method, getUsers(). Finally, I expected getData to have been called. When running the test I receive the following error: TypeError: this.httpService.getData(...).catch is not a function
. I think I am not using spyOn correctly. Here is the isolated test:
it('should have getUsers() call the service GetData()', inject([HttpService], fakeAsync((httpService) => {
let url = AppConfig.URL_UsersList //AppConfig is importerd
spyOn(httpService, 'getData').and.returnValue(url);
dashboardComponent.getUsers();
expect(httpService.getData()).toHaveBeenCalled();
})))
I was thinking it may have something to do with how I set up the spec class? Here is how I set it up
describe('Dashboard Component', () => {
let httpService: HttpService;
let dashboardComponent: DashboardComponent
let fixture: ComponentFixture<DashboardComponent>
//let element;
beforeEach(async() => {
TestBed.configureTestingModule({
declarations: [
DashboardComponent
],
providers: [
HttpService
],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(DashboardComponent);
dashboardComponent = fixture.componentInstance;
});
And here is the function I am trying to test:
getUsers() {
this.httpService.getData(AppConfig.URL_UsersList)
.catch((error: Response | any) => {
this.showAlertWindow(this.exceptionMessage);
console.error(error.message || error);
return Observable.throw(error.message || error);
})
.subscribe((res: any) => {
this.rowData = res;
this.redrawAgGrid();
});
}
My goal is to have my test sucessfuly check if getData is being called when using my getUsers method. Thank you!
EDIT: So the reason why I was getting this error was because my component returns an observable, I was just returned a string. Here is the updated line. I suspect it works properly, because now I am receiving an entirely unrelated error saying property API is undefined.
spyOn(httpService, 'getData').and.returnValue(Observable.of(url));