Mdb*_*Mdb 26 promise jasmine angularjs
根据Michal Charemza的帖子编辑.
我有一个代表angularui模态对话框的服务:
app.factory("dialogFactory", function($modal, $window, $q) {
function confirmDeleteDialog() {
var modalInstance = $modal.open({
templateUrl: "../application/factories/confirmDeleteDialog.htm",
controller: function($scope, $modalInstance) {
$scope.ok = function() {
$modalInstance.close("true");
};
$scope.cancel = function() {
$modalInstance.dismiss("false");
};
}
});
return modalInstance.result.then(function(response) {
return 'My other success result';
}, function(response) {
return $q.reject('My other failure reason');
});
};
return {
confirmDeleteDialog: confirmDeleteDialog
};
});
Run Code Online (Sandbox Code Playgroud)
如果用户从对话框中单击"确定",则调用delete方法requestNotificationChannel.deleteMessage(id).
$scope.deleteMessage = function(id) {
var result = dialogFactory.confirmDeleteDialog();
result.then(function(response) {
requestNotificationChannel.deleteMessage(id);
});
};
Run Code Online (Sandbox Code Playgroud)
问题是我无法对此进行单元测试.
这是我的考验.我已经正确地注入了q服务,但我不确定我应该从"confirmDeleteDialog"间谍返回什么...
describe("has a delete method that should call delete message notification", function() {
var deferred = $q.defer();
spyOn(dialogFactory, "confirmDeleteDialog").and.returnValue(deferred.promise);
spyOn(requestNotificationChannel, "deleteMessage");
$scope.deleteMessage(5);
deferred.resolve();
it("delete message notification is called", function() {
expect(requestNotificationChannel.deleteMessage).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
但我收到了expected spy deleteMessage to have been called.这意味着result.then......部分未被执行.我错过了什么?
Mic*_*mza 40
要模拟返回promise的函数,它还需要返回一个promise,然后需要将其作为单独的步骤进行解析.
在你的情况下deferred.resolve()你传递给间谍需要替换deferred.promise,并且deferred.resolve()单独执行.
beforeEach(function() {
var deferred = $q.defer();
spyOn(dialogFactory, "confirmDeleteDialog").and.returnValue(deferred.promise);
spyOn(requestNotificationChannel, "deleteMessage");
$scope.deleteMessage(5);
deferred.resolve();
$rootScope.$digest();
});
it("delete message notification is called", function() {
expect(requestNotificationChannel.deleteMessage).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
我怀疑你也需要打电话$rootScope.$digest(),因为Angular的承诺实现与摘要循环有关.
另外,与您的问题略有不同,但我认为您不需要在其中创建自己的延迟对象confirmDeleteDialog.您正在使用的(反)模式被标记为"遗忘的承诺",如http://taoofcode.net/promise-anti-patterns/
什么时候更简单,使用更少的代码,我认为这样可以更好地处理错误,您只需返回$modal服务创建的承诺:
var modalInstance = $modal.open({...});
return modalInstance.result;
Run Code Online (Sandbox Code Playgroud)
如果要根据已解析/拒绝的值修改调用函数所看到的内容,可以通过返回以下结果来创建链式承诺then:
var modalInstance = $modal.open({...});
return modalInstance.result.then(function(successResult) {
return 'My other success result';
}, function(failureReason) {
return $q.reject('My other failure reason');
});
Run Code Online (Sandbox Code Playgroud)
如果您不希望将函数的内部工作暴露给其调用者,通常需要执行此操作.这类似于在同步编程中重新抛出异常的概念.
| 归档时间: |
|
| 查看次数: |
28665 次 |
| 最近记录: |