2017-04-24 122 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>)触发摘要。

断言检查预期的结果。

你也可以考虑以模块化的安排,也许也该法案的一部分,并在你需要组成多个步骤更复杂的测试场景重用逻辑创建测试夹具

相关问题