I currently have a service that is depending on a variable set in $cookies. However, when I want to unit test the interaction between the service and the value stored in $cookies, then the service is always initialized before the actual initialization of the $cookie value.
So, my question is: how can I unit-test the interaction between the service and the $cookie value properly? (e.g.: how can I set the value in $cookies before my service is initialized?)
Note: I am using Angular 1.2 and Karma for unit testing.
Angular services can be tested in a couple of different ways, two most prominent being isolated tests and using the Angular TestBed . However, things get interesting when the service under test has dependencies (injected using Angular's dependency injection).
SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.
I created an example in JSFiddle which I hope helps you with your problem.
link
//--- CODE --------------------------
angular.module('myapp.test', [], function () {
}).controller('testcont', function($scope, $cookies) {
// Read a cookie and do something with it
$scope.favoriteCookie = $cookies.myFavorite;
});
// --- SPECS -------------------------
describe('controllers', function(){
var scope;
beforeEach(angular.mock.module('ngCookies', 'myapp.test'));
beforeEach(inject(function($controller, $rootScope, $cookies){
// Setting a cookie for testing
$cookies.myFavorite = 'oatmeal';
scope = $rootScope.$new();
$controller('testcont', {$scope:scope, $cookies: $cookies});
}));
it('sets the cookie on the scope', function(){
expect(scope.favoriteCookie).toBe('oatmeal');
});
});
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