2016-10-17 14 views
3

要素のコレクションをループして分度器を使用してすべての要素をクリックしている間に、子要素の数をカウントする際に問題が発生しています。私はそれをかなり新しくし、解決策を見つけようと多くの時間を費やしました。分度器が要素をクリックして子を数える

私の現在のコードは次のようになります。

明らか
function clickThroughElements(elements) { 
     var amountOfChildElements = 0; 
     for(var i in elements) { 
      var element = elements[i]; 
      element.click(); 
      element.all(by.css('div')).then(function(elements) { 
      amountOfChildElements += elements.length; 
      }); 
     } 
     return amountOfChildElements; 
     } 

amountOfChildElementsの増分が非同期で起こっているので、私は、戻り値に0を取得しています。誰も、どのように適切にamountOfChildElementsを返すことをお勧めできますか?

+0

ねえ、私はそれだけで要素内に含まれる子要素をカウントしている問題を理解していないことを確認?これは何か基本的なhttp://jsbin.com/taxonejiri/edit?html,js,console,outputを行うでしょう、あなたはこの投稿を見ましたか? http://stackoverflow.com/questions/7648761/how-to-select-all-children-in-any-level-from-a-parent-in-jquery –

答えて

3

約束が関与しているときには、ループを避ける必要があります。

カウントを取得する1つの方法は、まずmapを使用してすべてのカウントを約束の配列として取得することです。その後reduceで値をpromise.allでそれらを解決し、集計:

function clickThroughElements(elements) { 
    var counts = elements.map(e => { 
    e.click(); 
    return e.all(by.css('div')).count(); 
    }); 

    return protractor.promise.all(counts).then(values => { 
    return values.reduce((acc, value) => acc + value, 0); 
    }); 
} 

使用法:

clickThroughElements(elements).then(count => { 
    console.log(count); 
}); 
+0

チャームとして動作します!ソリューションをありがとうございました! – artumi

2

おそらく、分度器の.each().count()を使用して解決できます。これにより、すべてが非同期に保たれます。この線に沿って

何か:

var totalChildren = 0; 
var parents = element.all(by.css('div.class')); 
// iterate through parent, equivalent of a for loop 
parents.each(function (parent) { 
    // parent is the element with the current index of your loop 
    parent.click(); 
    // chain locator calls to parent, ensuring you are finding the correct child 
    // associated with the correct parent element 
    parent.all(by.css('div')).count().then(function (count) { 
     // count children of the current parent element 
     totalChildren += count; 
    }); 
}); 

参考:Protractor's element.all() functions

関連する問題