Working with document cookies

Answer to Idan's question

by eitanp461

HTML

<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.js"></script>
<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine-html.js"></script>
<link rel="stylesheet" href="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.css">
<script src="http://code.angularjs.org/1.2.0/angular.js"></script>
<script src="http://code.angularjs.org/1.2.0/angular-mocks.js"></script>
<script src="http://code.angularjs.org/1.2.0/angular-cookies.js"></script>

JavaScript

//--- CODE --------------------------
angular.module('myapp.test', []).provider('ConfigurationService', function () {

    function _getCookie(key) {
        var value = document.cookie;
        var cookieValue;
        if (value) {
            var cookieRegex = RegExp(key + '=([\\w,\\-\\_]*);?', 'i');
            cookieValue = value.match(cookieRegex);
        }
        return (cookieValue && cookieValue[1]) || '';
    }

    this.getCookie = _getCookie;

    var REST = 'rest/';
    var enableTenantIDInURL = true;

    //Put your configuration data here
    var configuration = {
        xsrfHeaderName: 'X-XSRF-TOKEN',
        xsrfCookieName: 'XSRF-TOKEN'
    };

    //the service
    this.$get = function () {
        return {
            get: function (key) {
                if (key === 'baseURL') {
                    return REST + _getCookie('tenantid') + '/';
                }
                if (key === 'tenantid') {
                    return _getCookie('tenantid');
                }
                return configuration[key];
            },
            getCookie: function (cookieName) {
                return _getCookie(cookieName);
            }
        };
    };
});

// --- SPECS -------------------------

describe('configuration-service', function () {

    // Service under test
    var configurationService;
    beforeEach(angular.mock.module('ngCookies', 'myapp.test'));
    beforeEach(function () {
        module(function ($provide) {
            //cookie api is weird like that.
            document.cookie = 'tenantid=12345;max-age=60';
            document.cookie = 'TENANT=mockTenant;';
            document.cookie = 'XSRF-TOKEN=232323;';
            //Create a mock PlatformLoggerService|
            $provide.value('PlatformLoggerService', {
                error: function (msg) {
                    // Do nothing
                },
                warn: function (msg) {
                    // Do nothing
                }
            });
        });
   ...