我想基于另一个函数的响应对多次调用的函数进行单元测试。
与我的问题类似:Call a promise function multiple times until condition met from another promise function。
这是函数
var monitorProgress = function() {
return getActiveTasks().then(function(res) {
if(res.length > 0) {
progress = res[0].progress;
if(progress !== 100){
return $timeout(function(){
return monitorProgress(); // multiple calls
},1000);
}
else {
// exit
console.log("done");
}
}
else{
console.log("done");
}
});
};
答案 0 :(得分:0)
以下是我测试此功能的方法:
describe('monitorProgress function', function() {
var response = null;
var promise = null;
var progress = 0;
beforeEach(function() {
// fake the implementation of monitorProgress
spyOn(SyncService,'monitorProgress').and.callFake(function() {
progress++;
// this mimics getActiveTasks promise and
// returns a promise with a res array length > 0
var deferred = $q.defer();
var res = [{ progress : progress }];
deferred.resolve(res);
// here the promise is returns
return deferred.promise.then(function(res) {
console.log("getActiveTasks res: " + JSON.stringify(res,null,2))
if(res.length > 0) {
progress = res[0].progress;
if(progress !== 100){
// keeps calling this until progress === 100
return SyncService.monitorProgress();
}
else {
// exit
console.log("exiting");
}
}
else {
// we never go here
}
});
});
// now that the spy is set, call the function
promise = SyncService.monitorProgress();
})
it("tracks that monitorProgress was called", function() {
expect(SyncService.monitorProgress).toHaveBeenCalled();
});
it("tracks that monitorProgress returned a promise", function() {
expect(promise).toBeDefined();
});
it("should return when progress is 100", function() {
// very important step
$rootScope.$apply();
// the final expectation
expect(progress).toBe(100);
});
});