如何在AngularJS中使用Jasmine测试cookie Getter和Setter

时间:2014-05-06 16:30:19

标签: angularjs cookies jasmine angularjs-service

我有一个带有getter和setter for cookies的服务:

angular.module('myApp.services').factory('CookieService', [function() {

    var setCookie = function(cname, cval, exdays) {
        exdays = typeof exdays !== 'undefined' ? exdays : 3;
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = 'expires=' + d.toGMTString();
        document.cookie = cname + '=' + cval + '; ' + expires;
    };

    var getCookie = function(cname) {
        var name = cname + '=',
            ca = document.cookie.split(';');
            for(var i = 0; i < ca.length; i++) {
                var c = ca[i].trim();
                if(c.indexOf(name) == 0) return c.substring(name.length, c.length);
            }
        return '';
    };

    return {
        setCookie: setCookie,
        getCookie: getCookie
    };
}]);

我如何测试获取/设置Cookie的工作原理,因为我使用的是document.cookie

到目前为止,我试过这个:

(function() {

    describe('CookiesService', function() {
        beforeEach(module('myApp.services'));

        var scope, CookieService, document;

        beforeEach(inject(function($rootScope, $injector) {
            scope = $rootScope.$new();
            CookieService = $injector.get('CookieService');
            document = {
                cookie: 'foo=bar'
            }
        }));

        it('should be set a cookie without expiration days', function() {
            CookieService.setCookie('thisdoes', 'notwork');
            expect(document.cookie).toBe('thisdoes=notwork');
        });
    });
}());

1 个答案:

答案 0 :(得分:1)

您需要在代码中使用$ document而不是文档,并向您的测试类添加注入,如下所示:

  beforeEach(inject([
        'CookiesService', '$document', function(_CookiesService_, _$document_) {
            CookiesService = _CookiesService_;
            $document = _$document_;
        }
    ]));

这是一个显示工作测试的傻瓜:http://plnkr.co/edit/GaO8wBMoBd8BGXaIkzf8?p=preview