2014-01-16 4 views
4

JavaScript와 AngularJS의 세계에 익숙하지 않아 내 코드가 아직 좋지 않지만 개선되고 있습니다. 그럼에도 불구하고 REST 백엔드가있는 간단한 로그인 페이지를 배우고 구현하기 시작했습니다. 로그인-양식을 제출 후, 인증 토큰은 반환이 내가 수동으로 테스트 할 때마다 잘 작동이

$http.defaults.headers.common['X-AUTH-TOKEN'] = data.authToken; 

같은 기본 HTTP 헤더의 속성으로 설정,하지만 그건 내가 갈 방법이 아니다된다 X-AUTH-TOKEN 헤더가 설정되어 있는지 확인하는 단위 테스트를 구현하고 싶습니다.

$ httpBackend를 통해 확인할 수 있습니까?

describe('LoginController', function() { 
    var scope, ctrl, $httpBackend; 

    // Load our app module definition before each test. 
    beforeEach(module('myApp')); 

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). 
    // This allows us to inject a service but then attach it to a variable 
    // with the same name as the service. 
    beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) { 
     $httpBackend = _$httpBackend_; 
     scope = $rootScope.$new(); 
     ctrl = $controller('LoginController', {$scope: scope}, {$http: $httpBackend}, {$location: null}); 
    })); 

    it('should create an authToken and set it', function() { 
     $httpBackend.expectPOST('http://localhost:9000/login', '200').respond(200, '{"authToken":"52d29fd63004c92b972f6b99;65e922bc-5e33-4bdb-9d52-46fc352189fe"}'); 
     scope.login('200'); 
     $httpBackend.flush(); 

     expect(scope.data.authToken).toBe('52d29fd63004c92b972f6b99;65e922bc-5e33-4bdb-9d52-46fc352189fe'); 
     expect(scope.loginValidationOverallError).toBe(false); 
     expect(scope.status).toBe(200); 
    }); 

내 컨트롤러는 다음과 같습니다 : 예를 들어, 나는 다음과 같은 검사를 내가 http://docs.angularjs.org/api/ngMock.$httpBackend에서 문서를 확인하지만, 마지막 테스트가 내 코드에 실제로 적용 할 경우 확실하지 않다

.controller('LoginController', ['$scope', '$http', '$location', 
    function ($scope, $http, $location) { 

     // Login Stuff 
     $scope.data = {}; 
     $scope.status = {}; 
     $scope.loginValidationOverallError = false; 
     $scope.login = function (user) { 
      $http.post('http://localhost:9000/login', user).success(function (data, status) { 

       $scope.data = data; 
       $scope.status = status; 
       $scope.loginValidationOverallError = false; 


       console.log($scope.status, $scope.data); 
       $http.defaults.headers.common['X-AUTH-TOKEN'] = data.authToken; 
       $location.path('/user'); 

      }).error(function (data, status) { 
        console.log(status + ' error'); 
        $scope.loginValidationOverallError = true; 
       }); 

     }; 
     ... 

(방법 그 코드는 실제로 무언가를 테스트합니다.)

it('should send auth header', function() { 
    var controller = createController(); 
    $httpBackend.flush(); 

    $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { 
     // check if the header was send, if it wasn't the expectation won't 
     // match the request and the test will fail 
     return headers['Authorization'] == 'xxx'; 
    }).respond(201, ''); 

    $rootScope.saveMessage('whatever'); 
    $httpBackend.flush(); 
}); 

답변

7

저는 같은 문제에 직면했고 마침내 해결했습니다. 그것은 AuthenticationService.login() 기능에 매우 까다로운

souce에 코드이었다

$http.post(...) 
    .success(function(data) { 
    ... 
    $http.defaults.headers.common['Authorization'] = data.oauth_token; 
    }); 

테스트 코드

beforeEach(inject(function(_$httpBackend_,AuthenticationService) { 
    $httpBackend = _$httpBackend_; 
    $authenticationService = AuthenticationService; 
})); 

it('should login successfully with correct parameter', inject(function($http) { 
// Given 
... 
... 
var fakeResponse = { 
    access_token: 'myToken' 
} 

$httpBackend.expectPOST('oauth/token',urlEncodedParams, function(headers) { 
     return headers['Content-Type'] === 'application/x-www-form-urlencoded'; 
}).respond(200, fakeResponse); 

// When 
$authenticationService.login(username,password); 


// Then 
$httpBackend.flush(); 
expect($http.defaults.headers.common['Authorization']).toBe('myToken'); 

트릭 여기 기본 헤더는 에 설정되어 있는지입니다 실제 $ http 서비스, 조롱 된 $ httpBackend가 아닙니다. 당신은 내가 테스트를 해봤

실제 $ HTTP 서비스를 주입해야하는 이유는 년대 $ httpBackend하지만 $ httpBackend이 '기본값'속성, 알겠습니다, 주입

+0

감사가없는 때문에 "정의되지 않은"오류가 발생했습니다 (기능 ($ http) 트릭입니다 – Luk

관련 문제