jasmine spy on nested object

眉间皱痕 提交于 2019-12-04 03:03:53

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.

Andreas Köberle

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!