dallinns
dallinns

Reputation: 152

How to check if a cookie was set in a controller in a unit test with Angular

I have a controller that sends a username and password to a rest service and returns a token:

.controller('Login', ['$scope', '$cookieStore', '$http', function($scope, $cookieStore, $http) {

    $scope.credentials = {};

    $scope.login = function(credentials){
        $http.post(constants.serverAddress + 'login', credentials).success(function(data, status){
            $cookieStore.put('token', data.token);

            $http.defaults.headers.common['Authorization'] = 'Token ' + data.token;
        });
    }

}])

I am trying to write a unit test for this controller. How do I read the values of cookieStore from within the unit test to assure that the cookie was set?

Upvotes: 0

Views: 2747

Answers (1)

jakee
jakee

Reputation: 18566

$cookieStore has also a get -method

So in a unit test, use it to retrieve the value

expect($cookieStore.get('token')).toBe('your-token');

Also make sure you inject the service to your tests

var $cookieStore;

beforeEach(inject(function($injector) {
  $cookieStore = $injector.get('$cookieStore');
}));

Upvotes: 3

Related Questions