vendredi 27 mai 2016

unit testing odd case of $http.get in angular

this whole story is on Angular 1.5.5.

so I have created a component and on its controller, on the $onInit function which basically contains this request

            apphelper.readFromConfig($http).then(function (config) {...});

Iam getting a [$http:badreq] Http request configuration url must be a string error

the apphelper is a typical javascript closure function that several different applications use to get predefined ajax calls and it looks like this

var apphelper = function () {
    var config;
 return {
        readFromConfig: function ($http) {
            return $http.get(this.getConfig()).
                then(function (response) {
                    return response.data;
                });
        },
 setConfig: function (_config) {
            config = _config;
        },
        getConfig: function () {
            return config;
        }
}
} ();

now here is the extremely odd part the setConfig() is fired inside a factory

app.factory('session', function GetSession($http, $q) {
        return {
            getConfig: function (configuration) {
                var defer = $q.defer();

                if (!configuration) {
                    configuration = "default";
                }
                $http({
                    url: "/config/" + configuration,
                    method: "GET",
                    data: "{}",
                    headers: { 'Content-Type': 'application/json' }
                }).success(function (data, status, headers, config) {
                    //staff
                    apphelper.setConfig("/config/" + configuration);
                    defer.resolve('done');
                }).error(function (data, status, headers, config) {
                    console.log(data);
                    defer.reject();
                });
                return defer.promise;
            }
        }
    });

and this factory is fired from the routeprovider

app.config(['$routeProvider',
            function ($routeProvider) {
                $routeProvider.
                    when('/:config', {
                        templateUrl: 'partials/components/my-map.html',
                        controller: 'MapController',
                        resolve: {
                            configData: function (session, $route) {
                                return session.getConfig($route.current.params.config);
                            }
                        }
                    });
            }]);

All this story is for two reasons

  • first I got a directive that needs some values before the dom is initialized (thus the resolve) thingy
  • second I need to check by the time the page component gets loaded if there were any changes in the config service

As odd as it might seem it works. Now i cannot figure out how to unit test this thing. Any help will be appreciated

Aucun commentaire:

Enregistrer un commentaire