0

I've been trying to test the process when any request was sended and I want check if the headers are ok. What have I done wrong?

check this 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();
        });
    }

});
  • Can you test a console.log in your handleRequest ? I think this is not working because ApiInterceptor is defined in a factory. Factory are not instantiated during config phase. I usually dump my interceptor definition in the config phase, i don't provide it in angular environment because it's not necessary since it won't be usefull in other places than there. – Walfrat Apr 01 '16 at 15:07
  • @Walfrat thanks for your advice. I'll try and then i tell you. Answering your question, no, the console.log never is executed. – Gonzalo Pincheira Arancibia Apr 01 '16 at 15:14

2 Answers2

1

you can inject Auth headers in configFn itself.

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

Finally, the solution was very simply! Injecting the $http service and execute a simply `get``

updated 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();

    }