Question

I have a service with getter and 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
    };
}]);

How can I test if getting/setting up the cookies works since I it is using document.cookie?

So far, I tried this:

(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');
        });
    });
}());
Was it helpful?

Solution

You need to use $document in the code everywhere instead of document, and add an injection to your test class like this:

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

Here's a plunker showing a working test: http://plnkr.co/edit/GaO8wBMoBd8BGXaIkzf8?p=preview

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top