2017-04-24 121 views
0

如何使用jasmine在angularjs中編寫以下代碼的測試用例,我已經完成了工作正常,但無法模擬$ q數據的數據模擬,因爲我的測試用例越來越失敗

$q.all([_allMasterList, _allUserList]).then(function(arrData){ 
     $scope.notificationLists = manageNotifications.getAllNotificationList(arrData, _fmno); 
    }); 

我試着從以下AngularJs

beforeEach(function() { 
     manageNotifications = jasmine.createSpyObj('manageNotifications', ['getNotificationMasterList', 'getNotificationUserList', 'getAllNotificationList' ]); 
    }); 

    beforeEach(inject(function($controller, _manageNotifications_, $window, $location, $rootScope, _mckModal_, $timeout, System_Messages, $q, $httpBackend, _confirmationModalService_, _API_ENDPOINT_){ 
    httpBackend = $httpBackend; 
     rootScope = $rootScope; 
     scope = $rootScope.$new(); 
     API_ENDPOINT = _API_ENDPOINT_; 
     manageNotifications = _manageNotifications_; 
    confirmationModalService = _confirmationModalService_; 

    /* Mock Data */ 
    manageNotifications.getNotificationMasterList = function(){ 
      deferred_getNotificationMasterList = $q.defer(); 
      deferred_getNotificationMasterList.resolve(_masterList); 
      return deferred_getNotificationMasterList.promise; 
    }; 

    manageNotifications.getNotificationUserList = function(_data){ 
      deferred_getNotificationUserList = $q.defer(); 
      deferred_getNotificationUserList.resolve({ 
     "status": "Success", 
     "dataValue": _data 
     }); 
      return deferred_getNotificationUserList.promise; 
    }; 

    })); 
+0

你已經有什麼? –

回答

0

承諾是緊密結合的消化週期。這意味着在摘要被觸發之前,沒有承諾會被解決或被拒絕。

由於您處於單元測試環境,因此您需要在執行斷言之前自行觸發摘要。

嘗試調用你的範圍以下之一,這取決於你的願望:

  1. rootScope.$digest() - 將執行消化
  2. rootScope.$apply(<some_exprssion>) - 將評估這是外部角框架的表達(如:該處理需要在角度方面來評估一些邏輯時DOM事件)

$apply是調用$digest及其執行的樣子:

function $apply(expr) { 
    try { 
    return $eval(expr); 
    } catch (e) { 
    $exceptionHandler(e); 
    } finally { 
    $root.$digest(); 
    } 
} 

注:你可以少寫

相反的:

manageNotifications.getNotificationMasterList = function(){ 
     deferred_getNotificationMasterList = $q.defer(); 
     deferred_getNotificationMasterList.resolve(_masterList); 
     return deferred_getNotificationMasterList.promise; 
}; 

你可以寫:

manageNotifications.getNotificationMasterList =() => $q.when(_masterList); 

或更好,更茉莉花般的,如果你需要監視已經創建的對象並自定義模擬:

spyOn(manageNotifications, 'getNotificationMasterList ').and.returnValue($q.when(_masterList)); 

摘要:

跟上AAA

通過設置你的嘲弄安排測試。

Act通過調用您的操作/方法,然後調用$scope.$digest()$scope.$apply(<expr>)觸發摘要。

斷言檢查預期的結果。

你也可以考慮以模塊化的安排,也許也該法案的一部分,並在你需要組成多個步驟更復雜的測試場景重用邏輯創建測試夾具

相關問題