如果设置了特定标头,则测试AngularJs的$ http.defaults.headers.common

Luk*_*Luk 5 angularjs

所以我是JavaScript和AngularJS的新手,因此我的代码还不如它应该的那么好,但它正在改进.然而,我开始学习并实现一个带有REST后端的简单登录页面.提交登录表单后,将返回一个身份验证令牌,并将其设置为默认的http-header属性,如下所示

$http.defaults.headers.common['X-AUTH-TOKEN'] = data.authToken;
Run Code Online (Sandbox Code Playgroud)

每当我手动测试时,这都可以正常工作,但这不是我要去的方法,所以我想实现一个单元测试,它检查是否设置了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);
    });
Run Code Online (Sandbox Code Playgroud)

我的控制器看起来像这样:

.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;
                });

        };
        ...
Run Code Online (Sandbox Code Playgroud)

我检查了http://docs.angularjs.org/api/ngMock.$httpBackend上的文档,但不确定最后一个测试是否实际适用于我的代码(以及该代码实际测试的内容)

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();
});
Run Code Online (Sandbox Code Playgroud)

doa*_*hai 8

我遇到了同样的问题,我终于解决了.这非常棘手

AuthenticationService.login()函数的源代码

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

测试代码

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');
Run Code Online (Sandbox Code Playgroud)

这里的诀窍是默认标头是在真正的$ http服务上设置的,而不是模拟的$ httpBackend.这就是你应该注入真正的$ http服务的原因

我已经尝试测试$ httpBackend但是出现了"未定义"错误,因为$ httpBackend没有'defaults'属性