【问题标题】:How to check headers in any request in angular?如何以角度检查任何请求中的标头?
【发布时间】:2016-04-02 05:11:11
【问题描述】:

我一直在尝试在发送任何请求时测试该过程,并且我想检查标头是否正常。我做错了什么?

检查此代码笔:http://codepen.io/gpincheiraa/pen/qZPrEp

App.js

 angular
    .module('exampleApp')
    .config(configFn);

  configFn.$inject = ['$httpProvider'];

  function configFn($httpProvider){ 
    $httpProvider.interceptors.push('ApiInterceptors');
  }

ApiInterceptors.js

  angular
    .module('exampleApp')
    .factory('ApiInterceptors', factory);

  factory.$inject = ['$q'];

  function factory($q) {
    var service = {
      request: handleRequest,
    };
    return service;

    function handleRequest(request){
      request.headers['Authorization'] = 'Token token= 59a2cc5ca5fd6c5cb4dadf636d94de1a';
      return request;
    }

  }

ApiInterceptors_spec.js

describe('State check', function(){
    var httpBackend;

    beforeEach(module('exampleApp'));
    beforeEach(inject(eachSpec));

    function eachSpec($httpBackend){
        httpBackend = $httpBackend;
    }

    it('Should be have an Authorization header on any request', spec1);

    function spec1(){
        httpBackend.expectGET('http://www.exampleAPI.com', null, function(headers){
            console.log(headers);
            expect(headers['Authorization']).toBeDefined();
        });
    }

});

【问题讨论】:

  • 你能在你的 handleRequest 中测试一个 console.log 吗?我认为这不起作用,因为 ApiInterceptor 是在工厂中定义的。在配置阶段不会实例化工厂。我通常在配置阶段转储我的拦截器定义,我不在角度环境中提供它,因为它不是必需的,因为它在其他地方没有用处。
  • @Walfrat 感谢您的建议。我会试试然后告诉你。回答你的问题,不,console.log 永远不会被执行。

标签: angularjs jasmine karma-runner httpbackend angular-mock


【解决方案1】:

您可以在 configFn 本身中注入 Auth 标头。

function configFn($httpProvider){ 
$httpProvider.defaults.headers['Authorization'] = 'Token token= 59a2cc5ca5fd6c5cb4dadf636d94de1a';
    $httpProvider.interceptors.push('ApiInterceptors');
  }

【讨论】:

  • 感谢您的回答,我知道这种设置标头的方法,但我需要的是测试发送时请求的行为
【解决方案2】:

最后,解决方案非常简单! 注入 $http 服务并执行一个简单的`get`

更新的codepen ---> http://codepen.io/gpincheiraa/pen/qZPrEp

    it('Should be have an Authorization header on any request', inject(spec2));

    function spec2($http) {

      httpBackend.expectGET('http://exampleApi.com/')
        .respond(function(method, url, data, headers, params){

          expect(headers).toBeDefined();
          expect(headers['Authorization']).toBeDefined();

          return {};
        });

      $http.get('http://exampleApi.com/');

      httpBackend.flush();

    }

【讨论】:

    猜你喜欢
    • 2016-12-28
    • 2016-09-19
    • 2023-02-17
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 2019-09-25
    • 1970-01-01
    相关资源
    最近更新 更多