2016-05-17 77 views
-1

我有下面的工廠,其中有一個依賴於私人功能。私有函數在$ http.get(url)中.success單位測試在angularjs工廠內部的私人功能然後功能

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]; 
}); 

我知道我們不能測試私有函數。我只想知道如何處理這種情況下的測試用例。我們是否可以模擬私人功能

+0

我的觀點:你不應該直接測試。您應該測試整個模塊,因爲在您提供的情況下,您可以輕鬆地將代碼從內部函數移動到其使用的位置。但是有一刻... [已經有關於這個主題的問題 - 你有沒有搜索過](http://stackoverflow.com/search?q= [茉莉花] +測試+私人+功能)? –

回答

0

您不能在工廠中模擬私人功能。

它們的作用域是由empConfigFactory組成的函數,它們在其他地方是不可見的。如果你想測試它們,那麼你必須以某種方式暴露它們。

總之,單元測試他們的唯一方法是創建另一個服務或工廠,將這些方法暴露給您當前的工廠。

你可以看看羅伯特回答這裏:How to test 'private' functions in an angular service with Karma and Jasmine