[Fixed] How can I mock nested function with Jasmine& Angular

Issue

constructor(private searchService: SearchService, private storageService: StorageService) { 
this.searchService.pagesOutput.subscribe(images => {
  this.images = images;
  this.pages = this.searchService.numberOfPages;
  
})

}

I have a service as a dependency injection. I would like to mock it for test.
I know how to mock service and some methods

 searchServiceMock = jasmine.createSpyObj('SearchService', ['pagesOutput']);
 searchServiceMock.pagesOutput.and.returnValue(someValue)

But how can I reach nested functions?(searchServiceMock.pagesOutput.subscribe?)

Solution

Since you’re going to be subscribing to the value, if you return an observable, the subscribe will work. To mock an observable, I use of.

import { of } from 'rxjs';
...
searchServiceMock = jasmine.createSpyObj('SearchService', ['pagesOutput']);
searchServiceMock.pagesOutput.and.returnValue(of(/* whatever value you want to be for images in subscribe callback */))

Leave a Reply

(*) Required, Your email will not be published