shabb shabb - 5 months ago 47
AngularJS Question

How to karma test .config where $httpProvider is used in a service layer?

This is how my service looks like

(function(){
'use strict';
angular.module('gls.service', [])
.config(config)
.service('popup', popup)
.service('API', api);

/* Config */

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

function config($httpProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.get = {
'Content-Type': 'application/json'
};
$httpProvider.defaults.headers.post = {
'Content-Type': 'application/json'
};
$httpProvider.defaults.headers.put = {
'Content-Type': 'application/json'
};
}


followed by the functions for popup and API services.
How to test the
config($httpProvider)
function? I am running the UI in ionic. Please suggest the beforeEach() area to define the
.config
also.
Has it got anything to do with $httpBackend?

Answer

I suggest you to test if requests have correct header:

// Assume $httpBackend and $http have been properly injected above
it('should have correct Content-Type header on GET request', function() {
    $httpBackend.expectGET('/api-call', function(headers) {
       return headers['Content-Type'] === 'application/json';
    }).respond(200, {});
    $http.get('/api-call');
    $httpBackend.flush();
});
// ... and do the same for POST and PUT requests
Comments