2016-05-04 9 views
0

角度アプリを使用しています。ユーザー認証データをコントローラ経由でサーバーに送信するサービス「AuthenticationService」があります。私はジャスミン単位テストの初心者です。なぜこの問題が起こるのか理解できません。ポストクレデンシャル問題のログイン認証用のジャスミンによるユニットテスト

error: cannot read Property 'andReturn' of 'Undefined;

私はいくつかのデータを投稿している可能性があります。

私のコントローラのコードは次のとおりです。

angular.module('webApp') 
.controller('LoginController', ['$rootScope', '$scope', 'AuthenticationService', function ($rootScope, $scope, AuthenticationService) { 
    $scope.user = {}; 
    $scope.errors = {}; 
    $scope.authenticationError = false; 
    $scope.rememberMe = true; 

    $scope.login = function (event) { 

     event.preventDefault(); 
     AuthenticationService.Login({ // service called $http.post to send credentials. 
            username: $scope.username, 
            password: $scope.password, 
            rememberMe: $scope.rememberMe 
     },function(response){ 

      if(response.userName==undefined){ 
       $scope.authenticationError = true; 
      }else{ 

       AuthenticationService.SetCredentials(response.userName,response.createToken); 
      } 

     }); 
    }; 
}]); 

マイサービスコードは次のとおりです。

angular.module('webApp').service('AuthenticationService',function($http,$cookieStore,$rootScope,$q,$location,$timeout){ 

'use strict'; 
this.Login =function(credentials, callback){ 
    console.log(credentials); 
    var usernameData=credentials.username; 
    var passwordData=credentials.password; 
    var data1={"userName":usernameData,"password":passwordData} 

    var deferred = $q.defer(); 

    $http.post('authenticate', data1).success(function (response) { 

    callback(response); 
    console.log(deferred.resolve(response)); 
     }).error(function(error){ 

     deferred.resolve(error); 
     callback(error); 
    }); 

    return deferred.promise; 
} 
}); 

と私のテストコードは次のとおりです。

describe('testController', function() { 
    var $controller, $scope, AuthenticationService; 
    var dt = {username: "user1", password: "user1", rememberMe: true}; 

    beforeEach(module('webApp', function($provide){ 
     AuthenticationService = jasmine.createSpyObj("AuthenticationService", ["Login"]); 

     AuthenticationService.Login.and.returnValue(dt); 
    })); 

    beforeEach(inject(function(_$controller_, $rootScope, _AuthenticationService_){ 
     $scope = $rootScope.$new(); 
     AuthenticationService = _AuthenticationService_; 
     $controller = _$controller_("LoginController", { 
      $scope : $scope, 
      AuthenticationService : AuthenticationService 
     }) 
    })); 

    it("should load the service", function(){ 
     expect(AuthenticationService.Login).toHaveBeenCalled(); 
    }) 
}); 

答えて

1

AuthenticationServiceサービスが嘲笑されていない、ローカル変数実際のサービスによってオーバーライドされます:

AuthenticationService = _AuthenticationService_; 

は、それが働いた

beforeEach(module('webApp', { 
    AuthenticationService : { Login: jasmine.createSpy().and.returnValue(dt) } 
})); 
+0

おかげで嘲笑することができます! –

関連する問題