Jasmine单元测试Promise函数,该函数基于另一个Promise函数的响应被多次调用



我想对一个根据另一个函数的响应被多次调用的函数进行单元测试。

类似于我的问题:多次调用promise函数,直到另一个promise函数满足条件。

这是的功能

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"); 
        }
    });  
};

以下是我如何测试此功能:

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);
    }); 
}); 

最新更新