Taras Savchenko
Taras Savchenko

Reputation: 23

How can I mock nested function with Jasmine& Angular

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?)

Upvotes: 1

Views: 447

Answers (1)

AliF50
AliF50

Reputation: 18849

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 */))

Upvotes: 1

Related Questions