Jasmine Spy on a nested object

My service object is as follows:

var appService = { serviceOne: { get: function(){} }, serviceTwo: { query: function(){} } } 

I would like to make fun of appService, something like:

 expect(appService.serviceTwo.query).toHaveBeenCalled(); 

How can I do it?

+8
javascript unit-testing jasmine
source share
4 answers

OK I got this working with this:

 appService: { serviceOne: jasmine.createSpyObj('serviceOne', ['get']), serviceTwo: jasmine.createSpyObj('serviceTwo', ['query']) } 

Hope this is the correct way.

+7
source share

Just replace the function with jasmine spies:

 var appService = { serviceOne: { get: jasmine.createSpy() }, serviceTwo: { query: jasmine.createSpy() } } 

later:

 expect(appService.serviceTwo.query).toHaveBeenCalled() 
+6
source share

I ran into very similar problems and got a working solution that makes it easy to track multiple levels.

 appService = { serviceOne: jasmine.createSpy().and.returnValue({ get: jasmine.createSpy() }, serviceTwo: jasmine.createSpy().and.returnValue({ query: jasmine.createSpy() } } 

This solution allows you to call the following code in unit test

 expect(appService.serviceOne).toHaveBeenCalledWith('foobar'); expect(appService.serviceOne().get).toHaveBeenCalledWith('some', 'params'); 

Note: this code has not been tested; However, I have a very simple implementation in one of my applications. Hope this helps!

+2
source share

The above examples show an explicit, named spy creature. However, you can simply continue the chain in the jasmine.spyOn function to go to the method level.

For a deeply nested object:

 var appService = { serviceOne: { get: function(){} } }; jasmine.spyOn(appService.serviceOne, 'get'); expect(appService.serviceOne.get).toHaveBeenCalled(); 
0
source share

All Articles