2016-04-01 1 views
0

リクエストが送信されたときにプロセスをテストしようとしていて、ヘッダーが正常かどうかを確認したい。私は何を間違えたのですか?どのリクエストでもヘッダーを確認するには?

チェックこのcodepen:あなたは認証ヘッドを注入することができ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(); 
     }); 
    } 

}); 
+0

を実行し、あなたのhandleRequestではconsole.logをテストすることはできますか? ApiInterceptorは工場で定義されているため、これは機能していないと思います。ファクトリはコンフィグレーションフェーズ中にインスタンス化されません。私は通常、configフェーズでインターセプタの定義をダンプします。角度の環境では提供しません。なぜなら、それ以外の場所では役に立ちませんので、必要ではないからです。 – Walfrat

+0

@ Walfratはあなたの助言に感謝します。私は試してみるつもりです。あなたの質問に答える、いいえ、console.logは決して実行されません。 –

答えて

1

configFn自体のers。

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

あなたの答えをありがとう、私はヘッダーを設定するこのメソッドを知っているが、私はそれがテストの送信時に要求の動作を必要とする –

0

最後に、解決策は非常に簡単でした。 は$ 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(); 

    } 
関連する問題