My service object looks like this:
var appService = {
serviceOne: {
get: function(){}
},
serviceTwo: {
query: function(){}
}
}
I would like to mock appService,something like:
expect(appService.serviceTwo.query).toHaveBeenCalled();
How would I go about doing it?
OK I got this working with this:
appService: {
serviceOne: jasmine.createSpyObj('serviceOne', ['get']),
serviceTwo: jasmine.createSpyObj('serviceTwo', ['query'])
}
I hope it is the right way to do.
Just replace the function with jasmine spies:
var appService = {
serviceOne: {
get: jasmine.createSpy()
},
serviceTwo: {
query: jasmine.createSpy()
}
}
later on:
expect(appService.serviceTwo.query).toHaveBeenCalled()
I ran into a very similar problem and got a solution to work that allows spying at multiple levels relatively easily.
appService = {
serviceOne: jasmine.createSpy().and.returnValue({
get: jasmine.createSpy()
},
serviceTwo: jasmine.createSpy().and.returnValue({
query: jasmine.createSpy()
}
}
This solution allows the following code to be called in a 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 simmilar implementation in one of my apps. Hope this helps!
The examples above show explicit, named spy creation. However, one can simply continue chaining in the jasmine.spyOn
function to get to the method level.
For a deeply nested object:
var appService = {
serviceOne: {
get: function(){}
}
};
jasmine.spyOn(appService.serviceOne, 'get');
expect(appService.serviceOne.get).toHaveBeenCalled();
来源:https://stackoverflow.com/questions/17120921/jasmine-spy-on-nested-object