-1

I have below factory where there is a dependency on private function. The private function is inside $http.get(url).success

define(['underscore'], function (_) {
    "use strict";
    function empConfigFactory($http, $q, $log, configManager, empConfig) {
        var empSal = null;


//how do i test the below method.
        function calculateEmpSal() {
            var deferred = $q.defer();
            emp = empConfig;
            if (emp.designation === "Director") {
                empSal.Salary = "soem value";
            }
            else if (emp.designation === "CoDirector") {
                empSal.Salary = "soem value";
            }
            deferred.resolve(empSal);
            return deferred.promise;
        }

        return {
            "get": function () {
                var url = "http://someUrl";
                var deferred = $q.defer();

                $http.get(url).success(function (data) {
                        empSal = data;
                        if ("someCondition") {
                        //dependency on below function
                            calculateEmpSal().then(function () {
                                deferred.resolve(empSal);
                            }, function () {
                                deferred.resolve(empSal);
                            });
                        } else {
                            deferred.resolve(brand);
                        }
                    })
                    .error(function (err) {
                        console.log(err);
                    });
                return deferred.promise;
            }
        };
    }

    return ['$http', '$q', '$log', 'empModule.config.configManager', 'empModule.remote.empConfig', empConfigFactory];
});

I am aware that we cannot test the private function. I just want to know how to handle the test cases in this scenario. Can we mock a private function

user804401
  • 1,990
  • 9
  • 38
  • 71
  • My opinion: you should not test it directly. You should test the whole module because in the case you've provided you could easily move the code from the inner function to the place it's used. But one moment... [there are already questions on this topic - have you searched](http://stackoverflow.com/search?q=[jasmine]+test+private+function) before? – try-catch-finally May 18 '16 at 20:11

1 Answers1

0

You can't mock private function in a factory.

Their scope is the function that comprises your empConfigFactory and they are invisible anyplace else. If you want to test them, then you have to expose them somehow.

In short the only way to unit test them is to create another service or factory that will expose these methods to your current factory.

You can have a look at Robert answer here : How to test 'private' functions in an angular service with Karma and Jasmine

Community
  • 1
  • 1
Tonio
  • 4,082
  • 4
  • 35
  • 60