2016-04-01 18 views
0

Herhangi bir istek gönderildiğinde ve başlıkların iyi olup olmadığını kontrol etmek istediğimde bu işlemi test etmeye çalışıyorum. Neyi yanlış yaptım?Herhangi bir istekte başlıkların açısal olarak nasıl kontrol edilir?

onay bu 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

güncellenen

get''? Bence bu çalışmıyor çünkü ApiInterceptor bir fabrikada tanımlanmıştır. Fabrika yapılandırma aşamasında örneklenmez. Genellikle önleyici tanımımı yapılandırma aşamasında çöpe atıyorum, bunu açısal ortamda sağlamam çünkü gerektiğinden başka yerlerde kullanılmayacak olması nedeniyle gerekli değil. – Walfrat

+0

@Walfrat tavsiyeniz için teşekkürler. Ben deneyeceğim ve sonra anlatırım. Sorunuzu cevaplayın, hayır, console.log hiçbir zaman yürütülmez. –

cevap

1

Eğer Auth kafa enjekte configFn kendi içinde.

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

Cevabınız için teşekkürler, üstbilgileri ayarlamak için bu yöntemi biliyorum, ancak ihtiyacım olan şey, gönderirken isteklerin davranışını test etmektir. –

0

Son olarak, çözüm çok basit! $ http hizmeti enjekte ve yürütmek bir basitçe `Eğer handleRequest bir console.log test edebilir 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(); 

    } 
İlgili konular