I am new to protractor and trying to learn the concepts of asynchronous call in protractor. I am not able to resolve the status of boolean variable which I have set to true in case of any test case fails and execution goes to catch for promise Below is the seudo-code snippet. E.g:
var test = function (){
var deferred = protractor.promise.defer();
var abort = false;
for (j = 0; j < testCount; j++) {
switch (element.toString()) {
case 'input':
handler.execute().then(function(result){
deferred.fulfill(result);
..
}).catch(function(err){
abort = true;
if(abort){ // goes into if loop
console.log('abort status'+ abort); // prints as true
}
deferred.reject(err);
})
.....
}
if(abort){ //control do not go into if loop outside switch caseeven though abort is true
console.log('abort status'+ abort);
break;
}
}
return deferred.promise;
}
This may be silly question but I am not able to get resolve this. Thanks again hopefully that's clear enough to understand my problem.
UPDATES
Updated the code with promise I have used and added break statement in 2nd if statement to exit the for loop if test case fails.
As the handler.execute() method is running in a background thread, your second if is running before you are setting the value for abort.
You should move the code in that second if into the catch clause.
Add a waiting loop between the switch and the if(abort) statements, that waits for the background operation to finish.
Use a recursive function instead of for loop.
var abort = false;
it('should....', function() {
sampleRecursive(0, testCount, abort)
});
function sampleRecursive(j, testCount, abort) {
switch (element.toString()) {
case 'input':
handler.execute().then(function(result){
deferred.fulfill(result);
...
}).catch(function(err){
abort = true;
if(abort){ // goes into if loop
console.log('abort status'+ abort); // prints as true
}
deferred.reject(err);
})
...
}
if (j < testCount && abort == false) {
sampleRecursive(j + 1, testCount, abort)
}
}
You can update the above function to fit well on your test.
But recursive functions are easier to use than for loop if you are expecting a break at the middle.