【问题标题】:How to spyOn a private function in service factory如何监视服务工厂中的私有函数
【发布时间】:2014-04-11 09:24:27
【问题描述】:

对于下面的服务工厂,我想检查是否调用了 foo()。并且还想验证 foo() 函数的返回值。有人会告诉我如何使用 spyOn 使用 Jasmine 来做到这一点吗?我是 Jasmine 框架的新手。

angular.module('myapp').
factory('messageservice', ['$http', '$q', function ($http, $q) {

function foo(query) {
    return 'foo';
}

function getServerMessages(query) {
    var query=foo();
    return $http.get(query))
                    .then(function (result) {
                        console.log('success');
                    }, function (err) {
                        debugger;
                        console.log('error');
                    });
}

return {
    getMessages: getFolderMessages,
    getMessageDetails: getServerMessages
};
}]);

谢谢,

奎师那

【问题讨论】:

    标签: angularjs jasmine


    【解决方案1】:

    您不能直接执行此操作,但您可以通过监视 $http 并查看作为参数传递的内容来间接执行此操作。如果你得到正确的参数,你也知道 foo() 被调用了,否则它不会有正确的值。

    spyOn($http, 'get').andReturn(aPromiseYouShouldResolveAtSomePointInYourTest);
    expect($http.get).toHaveBeenCalled();
    var queryItWasCalledWith = $http.get.mostRecentCall.args;
    // do some assertions on queryItWasCalledWith
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 2015-11-27
      • 2023-01-05
      • 2022-07-22
      • 2015-03-15
      • 1970-01-01
      • 2013-07-24
      相关资源
      最近更新 更多