如何使用jasmine编写angularjs中以下代码的测试用例,我已经完成了数据的模拟工作正常但由于我的测试用例失败而无法模拟$ q数据
$q.all([_allMasterList, _allUserList]).then(function(arrData){
$scope.notificationLists = manageNotifications.getAllNotificationList(arrData, _fmno);
});
我在下面试过
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)
AngularJs的承诺与摘要周期紧密相关。这意味着在触发摘要之前不会解决或拒绝任何承诺。
因为您处于单元测试环境中,所以在进行断言之前需要自己触发摘要。
根据您的需要,尝试调用您的示波器之一:
rootScope.$digest()
- 将执行摘要rootScope.$apply(<some_exprssion>)
- 将评估Angular框架外部的表达式(例如:处理时需要在Angular上下文中评估某些逻辑的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);
或更好,更像Jasmine,如果您需要监视已经创建的对象并自定义模拟:
spyOn(manageNotifications, 'getNotificationMasterList ').and.returnValue($q.when(_masterList));
<强>要点:强>
跟上 AAA
通过设置模拟来安排您的测试。
通过调用您的操作/方法 行动,然后调用$scope.$digest()
或$scope.$apply(<expr>)
来触发摘要。
断言以检查预期结果。
您还可以考虑创建测试夹具,以模块化安排,也可以使用Act部分,并在需要编写多个步骤的更复杂测试场景中重复使用逻辑。