4

I am fairly new to jasmine and wanted to create a test for the following below, I created the code in the test section but I get "TypeError: Cannot set property 'username' of undefined"..

I created a global namespace 'cp' in apps.js and used that in the service and controller.

//controller
cp.controller = {};
cp.controller.LoginController = function($scope, $location, $cookies){
        $scope.signIn = function(){
            $cookies.user = $scope.form.username;
            user.set($scope.form.username);
            $location.hash( "home" );
        }
};
//service 
cp.serviceFactory = {};
cp.serviceFactory.user = function user( $cookies){
    var userName = $cookies.user;
    return{
        set: function(name){
            userName = name;
        },
        get: function(){
            return userName;
        }
    }
};
//test script
describe('Cameo Controllers', function() {

    describe('LoginController', function(){
        var scope, cookies, ctrl, $httpBackend;
        beforeEach(module('CameoPaaS'));
        beforeEach(inject(function(_$httpBackend_, $rootScope, $controller, $cookies) {
            $httpBackend = _$httpBackend_;
           // cookies =  $cookies.username;
            scope = $rootScope.$new();
            cookies = scope.$cookies;
            ctrl = $controller(cp.controller.LoginController, {$scope: scope, $cookies: cookies});
        }));
        it('should log the user into the system', function() {
            expect(scope.username).toBeUndefined();
            scope.form.username = 'me';
            scope.signIn();
            //expect(user).toBe(undefined);
        });
    });
});

Question: how do I define and set the value for the $cookies.username in the test script to get around the error.

Freezystem
  • 4,494
  • 1
  • 32
  • 35
user1741614
  • 43
  • 1
  • 4

2 Answers2

2

First off make sure you are including angular-cookies.js these were separated from main distro in 1.0.0rc3

If it were me, I would wrap the cookies handling into a service and then use jasmine to mock/spy on the your cookie-wrapper service implementation. You might find this post helpful. Also, I found this testing cookies in unit and e2e. IMHO the problem with this is that it is too close to the metal, having to work with the browser cookies directly.

Community
  • 1
  • 1
Dan Doyon
  • 6,710
  • 2
  • 31
  • 40
2

I also run through the same problem, here is the workaround -

beforeEach(inject(function($cookies){
    $cookies.username = 'AngularJs'; 
}));

Please suggest if there is any better way.

Vinit Rai
  • 25
  • 1
  • 7