我如何使用Jasmine监视从另一个类中存在的一个类调用的方法?

时间:2015-04-14 17:47:58

标签: javascript angularjs unit-testing jasmine

我有一个方法

thisSvc.asyncOperation: function(id) {
   return thatSvc.getById(id);

是否有可能创建一个间谍来告诉我是否已经调用了theSvc.getById,或者这个设计是反模式的? AFAIK,间谍只能在一个物体上创建。

2 个答案:

答案 0 :(得分:1)

来自http://www.htmlgoodies.com/html5/javascript/spy-on-javascript-methods-using-the-jasmine-testing-framework.html#fbid=ib4OX6qA3oS

" spyOn()只能在方法已存在于对象上时使用。对于简单的测试,这是您最好的选择。"

答案 1 :(得分:1)

你可以窥探任何你想要的东西,在你的茉莉花测试中确保你得到那个服务:

var thisSvc, thatSvc;

beforeEach(inject(function(_thisSvc_, _thatSvc_){
    thisSvc = _thisSvc_;
    thatSvc = _thatSvc_;
});

it('.asyncOperation should call thatSvc.getById', function(){
    spyOn(thatSvc, 'getById');
    var id = 4;

    thisSvc.asyncOperation(id);

    expect(thatSvc.getById).toHaveBeenCalledWith(id);
})