mardi 30 août 2016

AngularJS - Does not test callback function from Service call in controller in unit test script using Jasmine

Error:In test.js call callback(fetch response) from servie function call in controller
Here there is three files. In that test.js test the controller.js file using karma-jasmin for unit testing for angular js

controller.js

'use strict';  
//  Login Angular Module Controller 

var loginModule =          angular.module('loginModule.controllers'['toaster','vcRecaptcha']);  

//  Controller Function :   loginCtrl  
//  Parameters          :   $scope, $rootScope, $cookieStore, $location,         AuthenticationServiceLogin, FlashService, toaster, vcRecaptchaService, $http,   $controller    

loginModule.controller('loginCtrl', function ($scope, $rootScope,  $cookieStore,   $location, AuthenticationServiceLogin, FlashService, toaster,   vcRecaptchaService, $http, $controller)   
{ 

     //redirect user to dashboard if already logged in    
     $rootScope.globals = $cookieStore.get('globals') || {};  
        if ($rootScope.globals.currentUser) {  
            $location.path('/home');  
     }  

     // Function Name : forget password
    $scope.forgetPassword = function(){
        $scope.dataLoading = true;
        AuthenticationServiceLogin.forgetPassword($scope.email, function (response) {
        if (response.success) {
         toaster.pop('success', "", "Email sent Successfully. Please check your email.");
         $scope.dataLoading = false;
        }else{
        toaster.pop('error', "", "Email is incorrect / Email not exist in Database");
        $scope.dataLoading = false;
        }

        });

    };  

    //AuthenticationService.ClearCredentials();
    //  Function Name : login
    $scope.login = function (){
        $scope.dataLoading = true;

       // callback(response);
            //  Service Calls Function :    userLogin
            //  Parameters          :       $scope.username,$scope.password               AuthenticationServiceLogin.userLogin($scope.username,$scope.password, function (response) {
                console.log(response.success);
                if(response.success)
                {
                    AuthenticationServiceLogin.SetCredentials(response);
                    toaster.pop('success', "", "Login Successful");
                    $location.path('/home');
                }

                    if (response.status ==200) {
                    //AuthenticationServiceLogin.SetCredentials(response);

                    //START STOMP to establish connection
                    var stompCtrl = $rootScope.$new();
                    $controller('StompController', { $scope: stompCtrl });
                    //END STOMP to establish connection

                    toaster.pop('success', "", "Login Successful");
                    $location.path('/home');
                }
                else if(response.status ==401){
                    toaster.pop('error', response.status+" "+response.statusText," Access is denied due to invalid credentials");
                    $scope.dataLoading = false;
                }
                else {
                    toaster.pop('error', "Username / Password", "Username or password is incorrect");
                    $scope.dataLoading = false;
                }
       });
    };

});

service.js

    'use strict';

    var loginModule = angular.module('loginModule.services',['vcRecaptcha']);

    loginModule.service('AuthenticationServiceLogin', function ($http,  $cookieStore,$rootScope,$timeout, UserService, Base64,vcRecaptchaService,ENV) {

    var service = {};
    var servicePath = ENV.apiEndpoint;

    this.forgetPassword = function(email,callback)
    {
        $timeout(function () {
        var response;
        if(email == 'admin@belvms.com'){
            response = {success: true};
        }

        else {
            response = {success: false};
        }
        callback(response);
    }, 900);
}

     this.userLogin = function(username, password,callback) {

         $timeout(function () {
          var response;

          if(username == 'admin' && password =='admin'){
            response = {success: true};
             }

          else {
            //response = {success: false, message: 'Username or password is  incorrect'};
               }
          callback(response);
          }, 900);

         var data1 = "username=" + username + "&password="
                + password + "&grant_type=password&scope=read%20write&" +
                "client_secret=belSecret&client_id=vms-bel";

    };

    this.SetCredentials = function (username, password) {
    var authdata = Base64.encode(username + ':' + password);

    $rootScope.globals = {
        currentUser: {
            username: username,
            authdata: authdata
        }
    };

    $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
    $cookieStore.put('globals', $rootScope.globals);
    }
   };
  });  

test.js

    'use strict';
     describe('Login', function () {
     var $controller1,AuthenticationServiceLogin,$window,$scope,$location;

     beforeEach(module('loginModule.controllers'));
     beforeEach(inject(function(_$controller_,_$q_,_$window_,_$location_) {
        $controller1 = _$controller_;
        $window = _$window_;
       AuthenticationServiceLogin = { userLogin: function() {},
                                 forgetPassword: function() {}
                                    };                           spyOn(AuthenticationServiceLogin,'userLogin').and.returnValue(response);
   spyOn(AuthenticationServiceLogin,'forgetPassword').and.returnValue(response);
    }));
     describe('Login', function () {
     it('To call Login function', function () {
         var $scope = {};
         var $rootscope = {};
         var $location = {}; 
         var $cookieStore = {};
         var $http = {};  
         var $controller = {};  
         var FlashService = {};     
         var controller = $controller1('loginCtrl',{
             $scope: $scope,
             $rootscope: $rootscope,
             $location: $location,
             $window: $window,
             $cookieStore:$cookieStore,
             AuthenticationServiceLogin: AuthenticationServiceLogin,
             FlashService:FlashService,
             $http:$http,
             $controller:$controller
      });
      $scope.login();
      });

      it('To call services', function() {

         var $scope = {};
         var $rootscope = {};
         var $location = {}; 
         var $cookieStore = {};
         var $http = {};  
         var $controller = {};  
         var FlashService = {};     
         var controller = $controller1('loginCtrl',{
             $scope: $scope,
             $rootscope: $rootscope,
             $location: $location,
             $window: $window,
             $cookieStore:$cookieStore,
             AuthenticationServiceLogin:AuthenticationServiceLogin,
             FlashService:FlashService,
             $http:$http,
             $controller:$controller
       });

       $scope.username="admin";
       $scope.password="admin";
       $scope.login();
     it('should have a getData function', function() {
expect(angular.isFunction(AuthenticationServiceLogin.userLogin)).toBe(true);
     });
      $scope.email='admin@belvms.com';
     var response1=function(response){}; 
     console.log(response1);
 expect(AuthenticationServiceLogin.userLogin).toHaveBeenCalledWith('admin','admin',response1);

     });

  });
});    

Here i attached image that display error when run test script.
enter image description here
so give solution why this erroe or why can't fetch reponse from userLogin function in test script

Aucun commentaire:

Enregistrer un commentaire