javascript 茉莉花间谍嵌套对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17120921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jasmine spy on nested object
提问by Amitava
My service object looks like this:
我的服务对象如下所示:
var appService = {
serviceOne: {
get: function(){}
},
serviceTwo: {
query: function(){}
}
}
I would like to mock appService,something like:
我想模拟 appService,例如:
expect(appService.serviceTwo.query).toHaveBeenCalled();
How would I go about doing it?
我将如何去做?
回答by Amitava
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.
我希望这是正确的做法。
回答by Andreas K?berle
Just replace the function with jasmine spies:
只需用 jasmine spies 替换该函数:
var appService = {
serviceOne: {
get: jasmine.createSpy()
},
serviceTwo: {
query: jasmine.createSpy()
}
}
later on:
稍后的:
expect(appService.serviceTwo.query).toHaveBeenCalled()
回答by Efonzie
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!
注:此代码未经测试;但是,我在我的一个应用程序中有一个非常相似的实现。希望这可以帮助!
回答by Adam
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.
上面的示例显示了显式的命名间谍创建。但是,您可以简单地在jasmine.spyOn
函数中继续链接以到达方法级别。
For a deeply nested object:
对于深度嵌套的对象:
var appService = {
serviceOne: {
get: function(){}
}
};
jasmine.spyOn(appService.serviceOne, 'get');
expect(appService.serviceOne.get).toHaveBeenCalled();