Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit-test the interaction of an Angular Service with $cookies?

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.

like image 801
Jeroen Avatar asked Nov 27 '13 08:11

Jeroen


People also ask

How do you unit test a service with a dependency?

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).

What is SpyOn in Angular unit testing?

SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.


1 Answers

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');      
  });
});
like image 123
Eitan Peer Avatar answered Sep 28 '22 16:09

Eitan Peer