2017-03-18 116 views
0

給出以下測試。
如何確保承諾得到解決,數據是提供的茉莉花在角度1.5控制器中測試模擬服務

describe("component: FicaStatusComponent", 
    function() { 
     var fs; 
     beforeEach(function() { 
      module("aureus", 
       function ($provide) { 
        $provide.service("ficaService", function() { 
         this.status = function() { 
          return $q(function (resolve, reject) { 
           resolve([{ documentType: { id: 1 } }]); 
          }); 
         } 
        }) 
       }); 

     }); 

     beforeEach(inject(function (_$componentController_, _ficaService_) { 
      $componentController = _$componentController_; 
      fs = _ficaService_; 
     })); 

     it("should expose a `fica` object", function() { 
      console.log('should expose'); 
      var bindings = {}; 
      var ctrl = $componentController("ficaStatus", null, bindings); 
      expect(ctrl.fica).toBeDefined(); 
     }); 

     it("compliant with no documents should not be compliant", 
      function() { 
       var ctrl = $componentController("ficaStatus"); 
       expect(ctrl.fica.length).toEqual(1); 
      }); 
    } 
); 

第二次測試符合任何文件...失敗。長度爲零。另一個測試通過,所以我有正確的控制器被實例化,屬性被定義。

模擬服務沒有正確解析數據,可能是因爲Promise仍在執行,或者沒有被調用的。

這裏是控制器組件的實現:

var FicaStatusController = (function() { 
    function FicaStatusController($log, $loc, ficaService) { 
     var _this = this; 
     this.$log = $log; 
     this.$loc = $loc; 
     this.ficaService = ficaService; 
     this.fica = []; 
     this.ficaService.status(1234).then(function (_) { return _this.fica = _; }); 
    } 

的服務如下:

var FicaStatusService = (function() { 
    function FicaStatusService($log, $http) { 
     this.$log = $log; 
     this.$http = $http; 
    } 
    FicaStatusService.prototype.status = function (accountNumber) { 
     var url = "api/fica/status/" + accountNumber; 
     this.$log.log("status: " + url); 
     return this.$http 
      .get(url) 
      .then(function (_) { return _.data; }); 
    }; 
    return FicaStatusService; 
}()); 

... 

回答

0

首先,u可以使用$ Q,如:

this.status = function() { 
    return $q.when([{ documentType: { id: 1 } }]); 
} 

二,解決承諾使用$ scope。$ digest,$ rootScope。$ digest:

var a = $q.when({test: 1}); 
expect(a.test === 1).toBe(false); 
$rootScope.$digest(); 
expect(a.test === 1).toBe(true); 
+0

不是$ scope。$ digest。它不會觸發根範圍內的摘要,並且不會執行承諾鏈。 – estus