简体   繁体   中英

How to synchronise for loop iteration one after another

I have a dropdown of country on a webpage. I need to validate the country names in drop down is sorted using Protractor-Cucumber.

I located all options in dropdown using element.all() and used a forEach loop on array. For each iteration, it extract the text and add to another array. Since extracting text takes some time, my resultant array does not have texts in same order as it appears in drop down.

element.all(by.css('ul.sbsb_b')).then(function(allOptions){
  allOptions.forEach(function(optn){
    optn.getText().then(function(text){
    result.push(text); 
     })
  })
 });

If my dropdown contains options as A,B,C,D then resultant array should give me in same order. Above logic works fine for less number of options. I want forEach to do iteration one by one instead of all at once because of asynchronous nature.

The method I would attempt for this issue would be to convert your ElementArrayFinder into an array of strings directly using .getText() . I would imagine this would preserve the order but cannot say for sure.

element.all(by.css('ul.sbsb_b')).getText().then(function(allOptions){
    console.log(typeof allOptions)
    console.log(Array.isArray(allOptions))
}

To preform your validation there are two approaches you could take which do not require any particular order of the state names array you are extracting.

You could sort the array and then expect them both to be equal.

element.all(by.css('ul.sbsb_b')).getText().then(function(allOptions){
    expect(allOptions.sort()).toEqual(expectedStates);
}

Or you could validate that the array you have created is the same length as your expected array of states and then verify that every expected state appears at least once in the created array

element.all(by.css('ul.sbsb_b')).getText().then(function(allOptions){
    expect(allOptions.length).toBe(expectedStates.length);
    for(let i = 0; i < expectedStates.length; count++){
       expect(allOptions).toContain(expectedStates[i]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM