Mocking Cookies with Angular
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.