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();
});
감사가없는 때문에 "정의되지 않은"오류가 발생했습니다 (기능 ($ http) 트릭입니다 – Luk