AngularJS - 不使用Jasmine测试单元测试脚本中控制器中Service调用的回调函数

时间:2016-08-30 10:49:34

标签: javascript angularjs unit-testing karma-runner karma-jasmine

错误:在test.js中调用来自控制器中的servie函数调用的回调(获取响应)
这里有三个文件。 在那个test.js中使用karma-jasmin测试controller.js文件,用于角度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);

     });

  });
});    

此处我附加了运行测试脚本时显示错误的图片。
enter image description here
所以给出解决方案为什么这个错误或为什么不能从测试脚本中的userLogin函数获取响应

0 个答案:

没有答案