Unit Test for Login with Jesmine and Karma

30 views
Skip to first unread message

ThanhDo

unread,
Apr 16, 2015, 10:32:25 PM4/16/15
to ang...@googlegroups.com
Hi everyone,
I'm trying to make my project with login function and now I want to make Unit Test for it. I'm using Karma for my test, but it failed. Could someone please help me to fix my test code right?
Thank in advanced!

Here is my login:

angular.module('myApp')
 
.controller('LoginCtrl', function($scope, $http, $location, $cookieStore) {
   
var self = this;
   $scope
.invalid = false;
   $scope
.username=$cookieStore.username;
   $scope
.password=$cookieStore.password;


   
this.login=function(){
     $http
.post('/login', {
       username
=$scope.username,
       password
=$scope.password
   
}).success(function(data) {
      $cookieStore
.put('username');
      $location
.url('/');
   
})
   
.error(function() {
      $scope
.password='';
      $scope
.invalid=true;
   
});
 
};
});


And here is my Test code:

'use strict';
describe
('Controller: LoginCtrl', function() {
 
var LoginCtrl, $httpBackend, $rootScope, $provide, $location, $cookieStore, scope;
  beforeEach
(module('myApp'));
 
  beforeEach
(inject(function($injector) {
    $httpBackend
=$injector.get('$httpBackend');
    $rootScope
=$injector.get('rootScope');
    $cookieStore
=$injector.get('$cookieStore');


   
LoginCtrl=function() {
     
return $controller('LoginCtrl', { // --> this is error: $controller is not defined
       
'$scope': $rootScope,
       
'$cookieStore': $cookieStore,
       
'$location': $location
     
});
   
};
 
}));
 
 
//This is success
  it
('should have a LoginCtrl controller', function() {
    expect
('myApp.LoginCtrl').toBeDefined();
 
});

 
// Failure
  it
('should store username and password into cookies', function() {
   
var $scope={};
   
var loginCtrl=LoginCtrl();
    $scope
.username='testUser';
    expect
($cookieStore.get('username')).toBe('testUser');
 
});

 
// Failure
  it
('should logs a user in and redirect', function() {
    angular
.element('username').enter('testUser'); // --> error: angular.element(...).enter is not a function
    angular
.element('password').enter('testPassword');
    angular
.element(':button').click();
    expect
(location.url).toBe('/'); // --> error: location is not defined
 
});
});

ThanhDo

unread,
Apr 20, 2015, 10:01:55 PM4/20/15
to ang...@googlegroups.com
Is anyone ?
Reply all
Reply to author
Forward
0 new messages