Jasmine async test using promises - javascript

I am doing some Jasmine testing using angular promises and have a question related to timing. Found an answer here Unit-test promise-based code in Angular, but need clarification about how this works. Given that the then method is always handled in an asynchronous way how is the following test guaranteed to pass. Isn't there are risk that the expect will run ahead of the then block being executed and run the expect before the value has been assigned. Or... does the digest cycle guarantee that the value will be assigned before the expect runs. Meaning, a digest cycle will effectively behave like a blocking call that guarantees that the promises are all resolved before the code is allowed to proceed.
function someService(){
var deferred = $q.defer();
deferred.resolve(myObj);
return deferred.promise;
}
it ('testing promise', function() {
var res;
var res2;
someService().then(function(obj){
res = "test";
});
someService().then(function(obj){
res2 = "test2";
});
$rootScope.$apply();
expect(res).toBe('test');
expect(res2).toBe('test2');
});

a digest cycle will effectively behave like a blocking call that guarantees that the promises are all resolved before the code is allowed to proceed.
Yes, although more accurately it would guarantee that the success callbacks of resolved promises would have run.
There is a very similar example that shows how the digest cycle is tied to the success callbacks of promises in the docs for $q

While Michal's answer points to the right idea, the key here is that $apply() is called on the pertinent scope. Here's the example from the Angular docs:
it('should simulate promise', inject(function($q, $rootScope) {
var deferred = $q.defer();
var promise = deferred.promise;
var resolvedValue;
promise.then(function(value) { resolvedValue = value; });
expect(resolvedValue).toBeUndefined();
// Simulate resolving of promise
deferred.resolve(123);
// Note that the 'then' function does not get called synchronously.
// This is because we want the promise API to always be async, whether or not
// it got called synchronously or asynchronously.
expect(resolvedValue).toBeUndefined();
// Propagate promise resolution to 'then' functions using $apply().
$rootScope.$apply();
expect(resolvedValue).toEqual(123);
}));

Related

Race condition issues with async functions Javascript [duplicate]

I would like to get a deeper understanding of how Promises work internally.
Therefore I have some sample code:
var p1 = new Promise(
function(resolve, reject) {
window.setTimeout(
function() {
resolve('res called')
}, 2000);
});
var p2 = new Promise(
function(resolve, reject) {
window.setTimeout(
function() {
resolve('res called')
}, 2000);
});
function chainPromises() {
return p1.then(function(val) {
console.log("p1");
return p2.then(function(val) {
console.log("p2");
return val;
});
});
}
chainPromises().then(function(val) {
console.log(val);
});
Here a link to execute this code.
As you would predict, first p1 is resolved, afterwards p2 and in the end the final then prints the resolv value.
But the API ref states the following:
"then" returns a new promise equivalent to the value you return from
onFulfilled/onRejected after being passed through Promise.resolve
So it would be interesting to know WHEN exactly the "then" function is executed?
Because the final "then" in the code is chained to the chainPromises(), I first thought that
it would execute after the function chainPromises() returns something (in this case another promise).
If this would have been the case the "val" of the final "then" function would be the returned promise.
But instead, the final "then" waits until all promises inside the first "then" which are returned have been resolved.
This absolutely makes sense because in this way, the "then" functions can be stacked, but
I do not really get how this is done, since the API spec. does not really cover what "then" returns and when the "then" functions is executed.
Or in other words, why does the final "then" function wait until all the Promises are resolved inside the chainPromises() function instead of just waiting for the first returned object as the API doc says.
I hope I could make clear what I mean.. :)
About Promise resolution
The thing you're witnessing here is called recursive thenable resolution. The promise resolution process in the Promises/A+ specification contains the following clause:
onFulfilled or onRejected returns a value x, run the Promise Resolution Procedure [[Resolve]](promise2, x)
The ES6 promise specification (promises unwrapping) contains a similar clause.
This mandates that when a resolve operation occurs: either in the promise constructor, by calling Promise.resolve or in your case in a then chain a promise implementation must recursively unwrap the returned value if it is a promise.
In practice
This means that if onFulfilled (the then) returns a value, try to "resolve" the promise value yourself thus recursively waiting for the entire chain.
This means the following:
promiseReturning().then(function(){
alert(1);
return foo(); // foo returns a promise
}).then(function(){
alert(2); // will only run after the ENTIRE chain of `foo` resolved
// if foo OR ANY PART OF THE CHAIN rejects and it is not handled this
// will not run
});
So for example:
promiseReturning().then(function(){
alert(1);
return Promise.resolve().then(function(){ throw Error(); });
}).then(function(){
alert("This will never run");
});
And that:
promiseReturning().then(function(){
alert(1);
return Promise.resolve().then(function(){ return delay(2000); });
}).then(function(){
alert("This will only run after 2000 ms");
});
Is it a good idea?
It's been the topic of much debate in the promises specification process a second chain method that does not exhibit this behavior was discussed but decided against (still available in Chrome, but will be removed soon). You can read about the whole debate in this esdiscuss thread. This behavior is for pragmatic reasons so you wouldn't have to manually do it.
In other languages
It's worth mentioning that other languages do not do this, neither futures in Scala or tasks in C# have this property. For example in C# you'd have to call Task.Unwrap on a task in order to wait for its chain to resolve.
Let's start with an easy perspective: "chainPromises" returns a promise, so you could look at it this way:
// Do all internal promises
var cp = chainPromises();
// After everything is finished you execute the final "then".
cp.then(function(val) {
console.log(val);
});
Generally speaking, when returning a promise from within a "then" clause, the "then" function of the encapsulating promise will be marked as finished only after the internal "then" has finished.
So, if "a" is a promise, and "b" is a promise:
// "a"'s "then" function will only be marked as finished after "b"'s "then" function has finished.
var c = a.then(function () {
return b.then(function () {
console.log("B!");
};
};
// c is a promise, since "then" always returns a promise.
c.then(function() {
console.log("Done!");
};
So the output will be:
B!
Done!
Notice btw, that if you don't "return" the internal promise, this will not be the case:
// "a"'s "then" function will only be marked as finished without waiting for "b"'s "then" to finish.
var c = a.then(function () {
// Notice we're just calling b.then, and don't "return" it.
b.then(function () {
console.log("B!");
};
};
// c is a promise, since "then" always returns a promise.
c.then(function() {
console.log("Done!");
};
Here we can't know what would be outputted first. It could be either "B!" or "Done!".
Please check the below example regarding how promises works:
The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
console.log('person1: shoe ticket');
console.log('person2: shoe ticket');
const promiseGirlFriendBringingTickets = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ticket');
}, 3000);
});
promiseGirlFriendBringingTickets.then((t) => {
console.log(`person3: show ${t}`);
})
console.log('person4: shoe ticket');
console.log('person5: shoe ticket');
Promise then return promise object, not promise's resolved value. I forked your JsFiddle, and added some of mine try this.
promise.then is executed right after that promise object is resolved.
I do not know how this is done in actual promises libraries, but I was able to re-create this functionality in the following way:
1) each promise has a waitingPromises property;
2) then method returns a new promise, and the original promise's waitingPromises property points to the new promise.
In this way, the chain of .then()s creates a structure that is similar to a linked list or rather a tree (each promise can have several waiting promises). A promise can be resolved only after its 'parent' promise has been resolved. The .then method itself is executed immediately, but the corresponding promise that it creates is resolved only later.
I am not sure this is a good explanation and would love to learn about other possible approaches.
Normally code is synchronous - one statement executes like (fileopen) and there is a guarantee that the next statement will execute immediately afterwards like filewrite()
but in asynchronous operations like nodejs, you should assume that
you have no idea when the operation will complete.
You can't even assume that just because you send out one request first, and another request second, that they will return in that order
Callbacks are the standard way of handling asynchrnous code in JavaScript
but promises are the best way to handle asynchronous code.
This is because callbacks make error handling difficult, and lead to ugly nested code.
which user and programmer not readble easily so promises is the way
You can think of Promise as a wrapper on some background task. It takes in a function which needs to be executed in the background.
The most appropriate place to use a promise is where some code is dependent on some background processing and it needs to know the status of the background task which was executed. For that, the background task itself accepts two callback resolve and reject in order to convey its status to the code which is dependent on it. In layman terms, this code is the one behind it in the promise chain.
When a background task invokes resolve callback with some parameter. it's marking the background operation successful and passing the result of the background operation to the next then block which will be executed next. and if it calls reject, marking it as unsuccessful then the first catch block will be executed.
In your custom promise, you can pass an error obj to the reject callback so that next catch block is aware of the error happened in the background task.

AngularJS 1.0.7: Nesting parallel promises with $resources

this post extends a previous one already solved. Please see it, to get in context: Nesting promises with $resources in AngularJS 1.0.7
With that approach in mind, I would like to make a parallel call to functions and when both are completed then run the searchBoats function with the results. I think I can nest the promises, but I also think it can be done in parallel, maybe with $q.all. Unfortunately, this promises topic is confusing for me and I donĀ“t know how to do it.
Taking the previous post example, I would like to do something like:
var parseURL = function() {
var deferred = $q.defer();
var promise = deferred.promise;
promise.then(function success(result) {
console.log(result);
searchBoats(result);
});
// Instead of resolve when parseBoatType promise is returned, I would like to
// wait for two promises
parseBoatType().then(deferred.resolve);
parseDestination().then(deferred.resolve);
// of course, with this code deferred will be resolved when first promise
// comes. Is it possible to use $q.all here?
};
parseURL();
As in your earlier question, there is no need to use a deferred here. Just use $q.all(), which returns a promise:
var parseURL = function() {
$q.all([parseBoatType(), parseDestination()])
.then(function (results) {
console.log(results);
searchBoats(results);
});
};
parseURL();

jasmine test does not move into the then part of the promise

I would like to test this function:
function initializeView() {
var deferred = $q.defer();
if(this.momentArray) {
core.listMoments(constants.BEST_MOMENT_PREFIX, '').then(function(moments) {
//Ommitted
deferred.resolve(moments);
}, function(error) {
console.log("ERROR");
deferred.reject(error);
});
}
else {
deferred.resolve();
}
return deferred.promise;
};
The function calls core.listMoments:
function listMoments(prefix, startAfter) {
// var deferred = $q.defer();
var promises = [];
return awsServices.getMoments(prefix, startAfter).then(function(moments) { //Mocked
console.log("getMoments Returned"); //Does not print
for(var i = 0; i < moments.length; i++) {
// moments[i].Key = constants.IMAGE_URL + moments[i].Key;
promises.push(getMomentMetaData(moments[i]));
}
return $q.all(promises);
});
};
Here is my test function:
it('Should correctly initialize the view', function(done) {
spyOn(awsServices, 'getMoments').and.callFake(function() {
console.log("getMoments Has been mocked"); //This prints
return $q.resolve(mock_moment);
});
service.initializeView().then(function() {
done();
})
});
The problem is with the awsServices 'getMoments' mock. The call to awsServices.getMoments is in the listMoments function. I would like to mock out this function but when I do it does not execute the "then" part of the promise.
So based on my console logs it would print the 'getMoments Has been mocked' log but it would not print 'getMoments Returned' log. So the function is mocked but for some reason it is not moving into the then statement and my test just times out.
In order to get the .then() part of a promise to work in such a test, you need to use a $rootScope.$apply(). This is needed whether the promise is in your test code or in a referenced library that is being tested. Think of it like the flush() function for $http or $timeout calls.
The Testing example from the Angular documentation's $q page shows how to use it:
it('should simulate promise', inject(function($q, $rootScope) {
var deferred = $q.defer();
var promise = deferred.promise;
var resolvedValue;
promise.then(function(value) { resolvedValue = value; });
expect(resolvedValue).toBeUndefined();
// Simulate resolving of promise
deferred.resolve(123);
// Note that the 'then' function does not get called synchronously.
// This is because we want the promise API to always be async, whether or not
// it got called synchronously or asynchronously.
expect(resolvedValue).toBeUndefined();
// Propagate promise resolution to 'then' functions using $apply().
$rootScope.$apply();
expect(resolvedValue).toEqual(123);
}));
Note that they inject $rootScope.
$q promises can be synchronous (when they are resolved synchronously) and depend on digest cycles.
There should generally be no asynchronous done callback in Angular tests.
Angular tests are supposed to be synchronous, so are $q promises. In order to achieve that a digest should be triggered manually when an existing promise (the ones that is returned from getMoments and initializeView) is chained with then. If done callback is placed inside then and a digest is not triggered, this will result in spec timeout.
spyOn(awsServices, 'getMoments').and.callFake(function() {
console.log("getMoments Has been mocked"); //This prints
return $q.resolve(mock_moment);
});
service.initializeView();
$rootScope.$digest();
The thing that can be improved here is isolation. There are several units (methods) involved in a single test. This will affect troubleshooting when one of them fails.
Usually unit testing implies that only one unit is tested at time, while the rest are mocked or stubbed. In this case in one test service.listMoments is called and awsServices.getMoments is mocked, and in another test service.initializeView is called and service.listMoments is mocked.

Defining then() after promise has been retrieved

I have a question about attaching callback functions to promises in AngularJS.
Suppose I have a service with a function that returns a promise. I make a call to this function and store the promise locally. Then I define a callback function on the promise.
var promise = TestService.get();
console.log('We have a promise!');
promise.then(function (result){
console.log('Here is the result:'+result);
});
In this case, we have a potentially risky situation. If the promise is resolved before we get to promise.then(..., the result is not outputted to the console (until the next digest cycle).
Alternatively, I could write the above code like this:
TestService.get().then(function (result){
console.log('Here is the result:'+result);
});
My question:
Has the risk been mitigated in the second example? And if not, how can I make sure that the promise does not resolve before I have attached a callback?
A slightly more elaborate answer than yes/no would be much appreciated :)
The behavior you are describing does not occur, that can be seen through a simple example. Here we have a simple promise factory which returns a promise which resolves immediately.
'use strict';
var make = function() {
return new Promise(function(resolve, reject) {
resolve(2);
});
};
Then we create a new promise and assign it to a variable
var prom = make();
We can call .then on it as many times as we want. This is because promises are immutable, we don't change the original value by chaining methods on it.
prom.then(a => console.log(a));
// 2
prom.then(a => console.log(a));
// 2
Suppose I have a service with a function that returns a promise. I make a call to this function and store the promise locally. Then I define a callback function on the promise.
No, you are not attaching a callback. When you call the then method you are doing something called promise chaining. Each call to then returns a new promise object that will resolve to the value returned by the previous promise.
For example;
var promise1 = TestService.get();
var promise2 = promise1.then(function(value) {
console.log('service resolved: '+value);
return "Hello World";
});
var promise3 = promise2.then(function(value) {
console.log(value);
});
promise3.then(function(value) {
console.log(value);
});
The above example will output the following.
**some value from TestService**
Hello World
undefined
We don't know who originally resolve the value for the first promise. All we know is that the service returned a promise. From that moment on we can chain the promises by adding more calls to then.
In this case, we have a potentially risky situation. If the promise is resolved before we get to promise.then(..., the result is not outputted to the console (until the next digest cycle).
No, it does not matter when or what digest the promise is resolved. A promise can have it's then method called multiple times even after being resolved. It will continue to resolve to the value as long as it has not been rejected. The decision to resolve or reject a promise is outside the scope of the success or failure callbacks.
You can create a promise, resolve it to a value, wait several digests and add a handler to then and it will still work as expected.
Has the risk been mitigated in the second example? And if not, how can I make sure that the promise does not resolve before I have attached a callback?
Think of promises as containers. They are going to hold the value you expect, and you have to call then to get it. If for what ever reason the value is unavailable you can find out why by using the error callback. The when aspect of promises is purely an asynchronize issue, and the idea is for promises to hide those issues.
JavaScript is not multithreaded, your asynchronous AJAX call isn't actually made by the browser until your code returns.
var promise = TestService.get();
for (var i= 0;i<100000;i++){
console.log(i)
}
console.log('We have a promise!');
promise.then(function (result){
console.log('Here is the result:'+result);
});
Watch this with the network analyzer.

What does "Promise fires on the same turn of the event loop" mean?

New to NodeJS. Going through the promise tutorial ('promise-it-wont-hurt') I have the following script:
var Q = require('q');
var deferred = Q.defer();
deffered.resolve('SECOND');
deffered.promise.then(console.log);
console.log('FIRST');
The output:
FIRST
SECOND
I don't get it, I would have thought that since resolved is fired first I should see second first.
They explain that this happens because of 'Promise fires on the same turn of the event loop'. I don't understand what that means...
Basically, the point is that the promise's then handler will not run before the current flow of code has finished executing and control is returned to the execution environment (in this case Node).
This is an important characteristic of Promises/A+ compliant promises because it ensures predictability. Regardless of whether the promise resolves immediately:
function getAPromise() {
var Q = require('q');
var deferred = Q.defer();
deferred.resolve('SECOND');
return deferred.promise;
}
getAPromise().then(console.log);
console.log('FIRST');
or whether it resolves after 10 seconds:
function getAPromise() {
var Q = require('q');
var deferred = Q.defer();
setTimeout(function () {
deferred.resolve('SECOND');
}, 10000);
return deferred.promise;
}
getAPromise().then(console.log);
console.log('FIRST');
you can be assured that FIRST will always be logged first.
This is discussed at length in chapters 2 and 3 of You don't know JS - async & performance. Asynchronous operations that sometimes run asynchronously and sometimes run synchronously are called Zalgos, and they are not considered to be a good thing.
It's important to note that the widely used promises in jQuery do not obey this behavior and have a number of other problems as well. If you find yourself with a jQuery promise, wrap it in a proper promise and proceed:
Q($.ajax(...)).then(breatheWithEase);
They explain that this happens because of 'Promise fires on the same turn of the event loop'. I don't understand what that means...
Me neither, imho this part doesn't make much sense. It probably should mean that when you call resolve or reject, the promise is settled immediately, and from then on will not change its state. This has nothing to do with the callbacks yet.
What is more important to understand is the next sentence in that paragraph:
You can expect that the functions passed to the "then" method of a promise will be called on the NEXT turn of the event loop.
It's like a simple rule of thumb: then callbacks are always called asynchronously. Always, in every proper promise implementation; this is mandated by the Promises/A+ specification.
Why is this? For consistency. Unlike in your example snippet, you don't know how or when a promise is resolved - you just get handed it back from some method you called. And it might have already been resolved, or it might be still pending. Now you call the promise's then method, and you can know: it will be asynchronous. You don't need to deal with cases that might be synchronous or not and change the meaning of your code, it simply is always asynchronous.

Categories

Resources