protractor and for loops

2019-09-13 10:07发布

问题:

I have a question concerning below code for test in Protractor. Namely as you can see firstly I find list of labels and then I check its number(three). Then I have a first loop where I compare each label with value from my table. Here I use i <table.length and then it works correctly. In the second loop I use labels.count() which is equal to three because i checked it earlier but it doesnt work at all. Protractor goes through this loop no matter what the output of the check is and the test finishes as PASSED. Can anyone tell me why i <table.length condition in the loop works and i<labels.count doesn't?

//labels list
var labels = element.all(by.xpath("//form[@name='form']//label"));

//test start
describe('angularjs homepage', function() {
it('test1', function() {
    browser.get('http://www.way2automation.com/angularjs-protractor/registeration/#/login');

  //shows 3
    labels.count().then(function(text){
            console.log( text); 
        });


    var table = ["Usern1ame","Password","Username *"];

    //first loop -> this one works if there is a difference between 'table' and element from 'label' list
    for (var i = 0; i <table.length; i++) {
      expect(labels.get(i).getText()).toEqual(table[i]); 
    }

    //this one doesn't -> if there is a difference between 'table' and 'label' 
    //list nothing happens, no errors, test passes
    for (var i = 0; i <labels.count(); i++) {
          expect(labels.get(i).getText()).toEqual(table[i]); 
        }





});

});

回答1:

In your example, labels.count() is a promise and you cannot use it directly. To get the value of count, you need to resolve the promise first. Look at below code,

labels.count().then(function(labelCount){
    for (var i = 0; i <labelCount; i++) {
      expect(labels.get(i).getText()).toEqual(table[i]); 
    }
})