问题
This is my code -
formElements[0].findElements(by.repeater(repeater)).then(function(items){
console.log(i, '>>>>>>>>>.No of items in the list --- '+items.length);
(function(items){
for(var x1=0; x1<itemsToBeSelected.length; x1++){
console.log(i, '>>>>>>.Looking for item --- '+itemsToBeSelected[x1]);
skip = false;
(function(items, x1){
for(var x2=0; x2<items.length; x2++){
(function(items, x2){
items[x2].getText().then(function(itemName){
console.log(i, '>>>>..Verifying '+itemsToBeSelected[x1]+' with '+itemName);
if(itemName == itemsToBeSelected[x1]){
console.log(i, '>>>>>.Selecting the item --- '+itemName);
items[x2].findElement(by.css('.regular-checkbox')).click();
}
});
}(items, x2));
}
}(items, x1));
}
}(items));
});
I want to break out of inner for loop when the condition itemName == itemsToBeSelected[x1] is satisfied. Tried using flag, return statements, but unable to break out from the loop.
Please suggest corrections in the code.
回答1:
ptor.element.all(by.repeater(repeater)).then(function(products){
console.log(i, '>>>>>>>>>.Products length --- '+products.length);
async.each(products, verifyName, function(err){
console.log('>>>>>>>>>>>err value --- '+err);
expect(err).toBe(true);
if(err){
console.log(i, '>>>>>>>>.Element is present');
}else{
console.log(i, '>>>>>>>>.Element is not present');
}
});
function verifyName(product, callback){
console.log(i, '>>>>>>>>.Inside function verifyName');
product.getText().then(function(name){
console.log('>>>>>>>>>>Looking for product --- '+name);
if(name==entityName){
console.log(i, '>>>>>>>>Verified the name - '+name);
callback(true);
}
});
}
});
We can achieve the same results with the help of async.each module as well. For e.g. I've posted a code in which i'm trying to find a single value.
So in relation to my question, we can click or perform any action on the element before setting callback(true). Say for e.g. here we could do - product.click();
回答2:
Nevermind what I said before the edit, you could use caolan's async module to iterate over your array, with the detect or detectSeries function.
It should look something like this :
formElements[0].findElements(by.repeater(repeater)).then(function(items) {
console.log(i, '>>>>>>>>>.No of items in the list --- ' + items.length);
itemsToBeSelected.forEach(function(itemToBeSelected) {
async.detect(items, function(item, next) {
item.getText().then(function(itemName) {
// This function will be called on each item in items, until next(true) is called
console.log('Verifying ' + itemToBeSelected + ' with ' + itemName);
// Here you call the callback with the truth value :
return next(itemName === itemToBeSelected);
});
}, function(item) {
// This function is called with the first item that resulted in a true
// callback value.
console.log('Selecting the item --- ' + item);
item.findElement(by.css('.regular-checkbox')).click();
});
});
});
来源:https://stackoverflow.com/questions/22553987/how-to-break-out-of-for-loop-in-protractor