0

I try to make a unit test on that code that consists of factory that take behavior Name and contracts an http request in a closure ?

    var app = angular.module("behaviour",[]);
    var behaviour = app.factory('Behaviours',['http',function(http){

    var BehavioursJson = $http.get('data.json');
    return {
        getBehaviour : function(behaviourName) {

            if (BehavioursJson[behaviourName]) {

                var behaviour = BehavioursJson[behaviourName];
                return function (behaviourData, callback) {
                    var keys = Object.allKeys(behaviourData);
                    var headers = {};
                    var data = {};
                    var url = behaviour.path;

                    // some process to fill headers and data objects

                    $http({
                        method: behaviour.method,
                        url: url,
                        data:  data,
                        headers: headers
                    }).then(function successCallback(response) {
                        callback(response,null);
                    },function errorCallback(error) {
                        callback(null,error);
                    });

                }
            };
        return null;
        }
    }
}]);

Note: using jasmine

vpsingh016
  • 703
  • 5
  • 9
Faesal
  • 679
  • 6
  • 19
  • There are a few problems with your factory. First, BehaviourJson is not a constructor so it should be camelCase; second, JSON is a string representation of an object, so you wouldn't call this variable JSON; and third (most importantly), you are assigning the return value of $http.get() to BehaviourJson, but $http returns a promise object not the http response. – Shaun Scovil Jan 27 '16 at 11:44
  • could you assign a sample to me please ? – Faesal Jan 27 '16 at 11:48
  • There are quite some tutorials out there on how to unit test services/factories in Angular. http://nathanleclaire.com/blog/2014/04/12/unit-testing-services-in-angularjs-for-fun-and-for-profit/ or http://www.sitepoint.com/unit-testing-angularjs-services-controllers-providers/. – Daan van Hulst Jan 27 '16 at 11:53
  • OK, i will get a look, thanks – Faesal Jan 27 '16 at 12:03
  • Not an answer to your question, but here is a cleaned up version of your factory: https://gist.github.com/sscovil/c64879bd7b527dd0dfd3 -- if you're going to make one HTTP request on instantiation and cache the results like this, you need to be prepared to handle cases in which the HTTP request has not yet resolved, or has failed. – Shaun Scovil Jan 27 '16 at 12:04
  • Also, this SO question/answer might be helpful: http://stackoverflow.com/questions/21577718/angularjsjasmine-httpbackend-not-working-as-expected – Shaun Scovil Jan 27 '16 at 12:07
  • shaun , i post a comment on your GitHub code. – Faesal Jan 27 '16 at 12:28

0 Answers0