我有了這樣的茉莉花單元測試不是在等待承諾的分辨率
(function() {
angular
.module('app')
.factory('myService', ['$q', 'asyncService',
function($q, asyncService) {
var myData = null;
return {
initialize: initialize,
};
function initialize(loanId){
return asyncService.getData(id)
.then(function(data){
console.log("got the data!");
myData = data;
});
}
}]);
})();
我想單元測試initialize
功能,我想在茉莉這樣一個異步依賴的角度服務:
describe("Rate Structure Lookup Service", function() {
var $q;
var $rootScope;
var getDataDeferred;
var mockAsyncService;
var service;
beforeEach(function(){
module('app');
module(function ($provide) {
$provide.value('asyncService', mockAsyncService);
});
inject(function(_$q_, _$rootScope_, myService) {
$q = _$q_;
$rootScope = _$rootScope_;
service = myService;
});
getDataDeferred = $q.defer();
mockAsyncService = {
getData: jasmine.createSpy('getData').and.returnValue(getDataDeferred.promise)
};
});
describe("Lookup Data", function(){
var data;
beforeEach(function(){
testData = [{
recordId: 2,
effectiveDate: moment("1/1/2015", "l")
},{
recordId: 1,
effectiveDate: moment("1/1/2014", "l")
}];
});
it("should get data", function(){
getDataDeferred.resolve(testData);
service.initialize(1234).then(function(){
console.log("I've been resolved!");
expect(mockAsyncService.getData).toHaveBeenCalledWith(1234);
});
$rootScope.$apply();
});
});
});
沒有控制檯消息出現,並且測試似乎只是在沒有承諾解決的情況下飛行。我雖然$rootScope.$apply()
會做,但似乎不是。
UPDATE
@estus是正確的,$rootScope.$appy()
足以引發所有承諾的分辨率。似乎這個問題是在我嘲笑的異步服務。我改變了它從
mockAsyncService = {
getData: jasmine.createSpy('getData').and.returnValue(getDataDeferred.promise)
};
到
mockAsyncService = {
getData: jasmine.createSpy('getData').and.callFake(
function(id){
return $q.when(testData);
})
};
,我設置testData
什麼,我需要爲測試而不是調用getDataDeferred.resolve(testData)
。在此更改之前,正在注入mockAsyncService,但getDataDeferred
的承諾從未得到解決。
我不知道這是否是在注射順序beforeEach
或什麼。更奇怪的是,這必須是callFake
。使用.and.returnValue($q.when(testData))
仍然可以解決問題。
是的,我已經刪除了我的答案,這部分是不相關的(它是在beforeEach競爭條件,而不是延遲本身創建擺在首位的問題),但使用'callFake'用'$ q.when'或'$ q.resolve'允許選擇實際的'$ q'實例,並在每次調用時使用新的承諾(如果間諜在同一規範中被多次調用,這很重要)。同樣,這兩種情況都應該按照預期的方式工作,放入'inject'中。 – estus
將'scope。$ apply()'添加到我的'it'方法的第一行。 「$ q.when」與我在做的事情沒有任何功能上的區別,但是讓方法更加整潔。非常感謝你們兩位。 – JonathanPeel