Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Cookies with Angular

In my main describe I have the following:

beforeEach(inject(function(...) {
    var mockCookieService = {
        _cookies: {},
        get: function(key) {
            return this._cookies[key];
        },
        put: function(key, value) {
            this._cookies[key] = value;
        }
    }

   cookieService = mockCookieService;

   mainCtrl = $controller('MainCtrl', {
       ...
       $cookieStore: cookieService
   }
}

Later on I want to test how a controller believes if the cookie already exists, so I nest the following describe:

describe('If the cookie already exists', function() {
    beforeEach(function() {
        cookieService.put('myUUID', 'TEST');
    });

    it('Should do not retrieve UUID from server', function() {
        expect(userService.getNewUUID).not.toHaveBeenCalled();
    });
});

However when I'm making the change to cookieService it's not persisting into the controller being created. Am I taking the wrong approach?

Thanks!

EDIT: Updated the testing code and this is how I'm using $cookieStore:

var app = angular.module('MyApp', ['UserService', 'ngCookies']);

app.controller('MainCtrl', function ($scope, UserService, $cookieStore) {
var uuid = $cookieStore.get('myUUID');

if (typeof uuid == 'undefined') {
    UserService.getNewUUID().$then(function(response) {
        uuid = response.data.uuid;
        $cookieStore.put('myUUID', uuid);
    });
}

});

like image 390
grivescorbett Avatar asked Sep 30 '13 21:09

grivescorbett


1 Answers

Your unit tests need not have to create a mock $cookieStore and essentially re-implement its functionality. You can use Jasmine's spyOn function to create a spy object and return values.

Create a stub object

var cookieStoreStub = {};

Set up your spy object before creating the controller

spyOn(cookieStoreStub, 'get').and.returnValue('TEST'); //Valid syntax in Jasmine 2.0+. 1.3 uses andReturnValue()

mainCtrl = $controller('MainCtrl', {
 ... 
 $cookieStore: cookieStoreStub 
}

Write unit tests for the scenario in which cookie is available

describe('If the cookie already exists', function() {
    it('Should not retrieve UUID from server', function() {
        console.log(cookieStore.get('myUUID')); //Returns TEST, regardless of 'key'
        expect(userService.getNewUUID).not.toHaveBeenCalled();
    });
});

Note: If you'd like to test multiple cookieStore.get() scenarios, you might want to move the creation of the controller into a beforeEach() inside the describe() block. This allows you to call spyOn() and return a value appropriate for the describe block.

like image 97
WeNeigh Avatar answered Oct 09 '22 20:10

WeNeigh