0

I'm testing some angularjs app using protractor and have encountered such a problem:

var counter = 0;
redButton.click();
allImages.each(function(element) {
    element.isDisplayed().then(function(isDispl){
        if(isDispl === true){
            expect(element.getInnerHtml()).toContain('red');
            counter++;
            console.log("I'm here!")
        }
    });
});
console.log(counter);

The output is:

0
I'm here!
I'm here!

while I expected output:

I'm here!
I'm here!
2

Why so? Why variable counter does not equal 2 -- the number of times the condition isDispl === true is fullfiled?

1 Answers1

2

Only one function can run at a time in JavaScript (that's simplifying a little, there are exceptions).

The main function runs all the way through before anything else happens. Since that function includes console.log(counter);, it logs the value of counter at that time.

Once the function has finished, the event loop can look for events that have fired.

The elements have been displayed so their promises trigger. Each time that happens (twice) you get a message and the value of counter changes.

Since this happens after the only time you output the value of counter, you never observe it reaching 2.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335