getting the size of an array of promises(protracto

2019-05-30 04:13发布

问题:

I have a list of checkboxes that I want to check if they are checked. I want to loop through the array of objects and check one by one but I cannot get the size of the array. I have tried the following 2 ways but I get different errors.

var i, n;
    networkStatusDetail.detailsList.all(by.tagName('div')).then(function(arr){
        console.log(arr.length);
        for(i=0;i<; i++){
            arr.get(i).element(by.model('displayedsites[site.siteid]')).isSelected().then(function(checked){
                expect(checked).toBe(true);
            });
        }
    });

With this code above I get an error saying that arr.get() is not a valid function.

The following code does not work because I am unable to get the size of the array. Assigning the size of the array to another variable only works within a promise function, but once the variable is used outside the value is gone.

networkStatusDetail.detailsList.all(by.tagName('div')).then(function(size){
        n = size;
        console.log('n = '+n);
    });

    console.log('n outside '+ n);
for(i=0;i<n; i++){
        check.get(i).element(by.model('displayedsites[site.siteid]')).isSelected().then(function(checked){
    expect(checked).toBe(true);
   //   console.log(i);
        });
   }

the 2 consoles will print 512 and undefined respectively, showing that the value of n outside of the promise function does not work.

I can only make it work if I manually set the max value of the for loop, but this value can change over time so It's not correct.

If anybody could give me a hand on how to do this it would be greatly appreciated.

回答1:

You don't need to know how many checkboxes are there to loop over them - use map() or each() instead:

element.all(by.model('displayedsites[site.siteid]')).each(function (checkbox) { 
    return checkbox.isSelected().then(function (isSelected) {
        console.log(isSelected);
    });
});