Chip 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 I want to check how the controller believes that the cookie already exists, so I will enclose the following description:

 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 make a change to cookieService , it is not saved in the controller being created. Am I taking the wrong approach?

Thanks!

EDIT: Updated test code, and that is how I use $ 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); }); } 

});

+6
source share
1 answer

In your unit tests, it is not necessary to create mock $ cookieStore and substantially reinstall its functionality. You can use the Jasmine spyOn function to create a spy object and return values.

Create a stub object

 var cookieStoreStub = {}; 

Configure 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 a script in which a 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 want to test several cookieStore.get() scripts, you may need to move the controller creation to beforeEach() inside the describe() block. This allows you to call spyOn() and return a value corresponding to the descriptive block.

+1
source

Source: https://habr.com/ru/post/954979/


All Articles