I try to test a function that uses nested promises (let's assume this function can't be changed). To process those promises I have to call $rootScope.$digest()
at least two times. I came up with this working solution calling $digest()
every 10ms.
// Set some async data to scope.key
// Note: This function is just for demonstration purposes.
// The real code makes async calls to localForage.
function serviceCall(scope, key) {
var d1 = $q.defer(), d2 = $q.defer();
setTimeout(function () {
d1.resolve('d1');
});
d1.promise.then(function (data) {
setTimeout(function () {
d2.resolve(data + ' - d2');
}, 100); // simulate longer async call
});
d2.promise.then(function (data) {
scope[key] = data;
});
}
it('nested promises service', function (done) {
var interval = setInterval(function () {
$rootScope.$digest();
}, 10),
myKey = 'myKey',
scope = {};
serviceCall(scope, myKey);
setTimeout(function () {
expect(scope[myKey]).toEqual('d1 - d2');
window.clearInterval(interval);
done();
}, 120); // What is the right timeout?
});
The problem is to estimate the timeout duration needed to digest enough times to resolve all promises. It gets further complicated if the service makes a real async call to e.g. localstorage.
Is there another way to solve this? Is there a way to get all remaining promises?