如何在AngularJS / Jasmine中模拟$ cookiestore.put

时间:2017-02-01 14:29:04

标签: angularjs unit-testing jasmine

我想测试我的Authentication.Login服务功能。

在此服务中调用另一个服务和cookiestore.put方法。

我想模仿这两个功能。但我仍然得到一个错误:/

我已经尝试使用Jasmine中的spyon函数,但它不起作用:

spyOn('base64', 'encode').and.returnValue(username + ';' + password);
spyOn('cookie', 'put').and.returnValue(username);

有人能帮助我吗?

这是身份验证服务:

function (Base64, $http, $cookieStore, $rootScope, $q) {
        //initialize service
        var service = {};

        service.Login = function (username, password) {
            //initialize promise object for asynchron behavior of the data 
            var deferred = $q.defer();

            var authdata = Base64.encode(username + ':' + password);

            //put login data in global variable to access in the root scope
            $rootScope.globals = {
                currentUser: {
                    username: username,
                    authdata: authdata
                }
            };

            //put base64 data in header
            $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
            //put login data in cookie to keep user logged in, if he refresh the page
            $cookieStore.put('globals', $rootScope.globals);

1 个答案:

答案 0 :(得分:0)

使用$provide覆盖服务:

var cookieStoreMock = {
  put: function() {
    return username;
  }
}

module(function($provide) {
  $provide.value('$cookieStore', cookieStoreMock);
});

describe(...