加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:19:56 所属栏目:安全 来源:网络整理
导读:所以我是 JavaScript和AngularJS的新手,因此我的代码还不如它应该的那么好,但它正在改进.然而,我开始学习并实现一个带有REST后端的简单登录页面.提交登录表单后,将返回一个身份验证令牌,并将其设置为默认的http-header属性,如下所示 $http.defaults.headers.
所以我是 JavaScript和AngularJS的新手,因此我的代码还不如它应该的那么好,但它正在改进.然而,我开始学习并实现一个带有REST后端的简单登录页面.提交登录表单后,将返回一个身份验证令牌,并将其设置为默认的http-header属性,如下所示

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

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

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

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

        };
        ...

我在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();
});

解决方法

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

AuthenticationService.login()函数的源代码

$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没有’defaults’属性

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读