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);
});
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With