Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having difficulty mocking Promise.all

I would like to mock out this function:

    function getMetaData(key) {
        var deferred = $q.defer();
        var s3 = vm.initiateBucket();
        var params = {
            Bucket: constants.BUCKET_NAME,
            Key: key
        };
        s3.headObject(params, function(error, data) {
            if(error) {
                deferred.reject(error);
            }
            else {
                console.log(data);
                deferred.resolve(data.Metadata);
            }
        });
        return deferred.promise;
    };

I am using a spyOn to mock out this function:

    spyOn(awsServices, 'getMetaData').and.callFake(function() {
        console.log("MOCKED");
        return $q.resolve({
            key: "MOCKED_KEY",
            description: "MOCK_DESCRIPTION",
            views: 1
        });
    });

The spy seems to be working - It is calling the "MOCKED" console.log. Here is the function which calls getMetaData:

function getPicsRadius(){
//Ommitted
    var promises = [];

    promises.push(awsServices.getMetaData(momentsInStates[i].Key)
      .then(function(metaData) {
        console.log(metaData);
        return {
            key: metaData.key,
            description: metaData.description,
            views: metaData.views
        };
    }))

}
return promise.all(promises);

This is called by another function using promise chaining:

function getNearbyMoments() {   
    //omitted
    return calculateNearbyStates()
    .then(getPicsByState)
    .then(concatPics)
    .then(getPicsWithinRadius).then(function(){
        console.log("SHOULD LOG BUT IS NOT");
    });
}

The console.log at the end there is not printing. The only error I'm getting is an Async timeout error. So it should be getMetaData(MOCKED) -> getPicsRadius -> getNearbyMoments(Not going into the then function). I suspect this has something to do with the Promise.all that I am returning since I never have trouble spying on regular promises. Any insights?

like image 647
MatTaNg Avatar asked Mar 05 '26 22:03

MatTaNg


1 Answers

ES6 promises are not integrated with the AngularJS framework and its digest cycle.

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

Instead of Promise.all, use the $q.all method.

like image 196
georgeawg Avatar answered Mar 08 '26 11:03

georgeawg