[英]Testing callback from service in an AngularJS controller spec
我有一個Controller,該Controller使用的服務具有成功時的回調函數。
控制器功能
itemCtrl.save = function () {
ItemService.save({ username: SessionService.getUsername() }, itemCtrl.item, function (res) {
$scope.$emit('UPDATE_ITEMS');
$modalInstance.close(res);
});
};
規范
it('should close the modal on successful save', function () {
spyOn(itemSrv, 'save').and.callFake(function () {
deferred = q.defer();
deferred.resolve();
return deferred.promise;
});
spyOn(modalInst, 'close').and.callThrough();
ItemCtrl.save();
scope.$digest();
expect(modalInst.close).toHaveBeenCalled();
});
當我在業力中運行此測試時失敗,因為未調用modalinstance的close函數。 我認為問題出在規格說明上,因為該功能正在應用中運行。 我對此有一些疑問:
-編輯-
我已經更改了我的服務電話,以使他們按照承諾來處理結果:
itemCtrl.save = function () {
ItemService.save({ username: SessionService.getUsername() }, horas.trabajo).$promise.then(function (res) {
$scope.$emit('UPDATE_ITEMS');
$modalInstance.close(res);
});
};
我猜我沒有通過測試,因為我的服務沒有返回promise(它具有一個promise屬性,我正在調用該屬性來發出事件並關閉modalInstance)。 但是我仍然對如何使用ng-resource返回承諾感到困惑。
我試圖解決這個問題的方法是返回一個帶有$ promise屬性的對象,該屬性包含q提供的承諾。
規范
it('should close the modal on successful save', function () {
spyOn(itemSrv, 'save').and.callFake(function () {
deferred = q.defer();
deferred.resolve();
return {$promise: deferred.promise};
});
spyOn(modalInst, 'close').and.callThrough();
ItemCtrl.save();
scope.$digest();
expect(modalInst.close).toHaveBeenCalled();
});
您會混淆promise和callbacks的概念,但是要使它按當前的方式工作,可以使用以下命令:
spyOn(itemSrv, 'save').and.callFake(function (params, callback) {
callback({some: 'response'});
});
打回來
您傳入一個將根據場景調用的函數
諾言
取回一個對象,該對象上包含一個方法(然后),該方法將在成功時調用第一參數或在錯誤時調用第二參數
兩者都有更多,但這是一個概述。
另外,我建議更改服務中的save
方法以返回承諾而不是接受回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.