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

冷暖自知 提交于 2019-12-06 10:27:51

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/37907163/how-to-karma-test-config-where-httpprovider-is-used-in-a-service-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!