2016-07-08 19 views
3

いくつかのデータを出力するページをテストしています。そのデータをJSONオブジェクトに取り込みたいと思います。残念ながら分岐器で約束からネストされたJSONを取得する方法

var cardDataToJSON = function() { 
    var result = {}; 

    $$('cards card').each(function (card) { 
     card.$('#name').getText().then(function (text) { result["name"] = text; }); 

     var web = {}; 
     card.$('#web').getText().then(function (text) { 
      web["text"] = text; 
     }); 
     card.$('#web').getAttribute('href').then(function (href) { 
      web["href"] = href; 
     }); 

     result.web = web; 
    }); 

    return result; 
}; 

、私の実際:だから私は、次のコードを書いた

[ { 
    name: "Joe", 
    web: { 
     text: "joessite.com", 
     link: "http://joessite.com" 
    } 
    }, 
    { 
    name: "Frank", 
    web: { 
     text: "frankssite.com", 
     link: "http://frankssite.com" 
    } 
    } ] 

:データは以下のように私は私の結果のJSONオブジェクトになりたい

<cards> 
    <card> 
    <div id="name">Joe</div> 
    <div id="web"> 
     <a target="_blank" href="http://joessite.com">joessite.com</a> 
    </div> 
    </card> 
    <card> 
    <div id="name">Frank</div> 
    <div id="web"> 
     <a target="_blank" href="http://frankssite.com">frankssite.com</a> 
    </div> 
    </card> 
</cards> 

(HTMLで)表示されます結果は(最初の "web"は空白です)。

[ { 
    name: "Joe", 
    web: { } 
    }, 
    { 
    name: "Frank", 
    web: { 
     text: "frankssite.com", 
     link: "http://frankssite.com" 
    } 
    } ] 

私は間違っていますか、私のコードで改善する必要がありますか?

(私は分度器のバージョン3.2.2を使用しています)

答えて

2

私はprotractor.promise.all()map()を使用します。

var cardDataToJSON = function() { 
    return $$('cards card').map(function (card) { 
     var name = card.$('#name').getText(), 
      web = card.$('#web a').getText(), 
      href = card.$('#web a').getAttribute('href'); 

     return protractor.promise.all([name, web, href]).then(function (values) { 
      return { 
       name: values[0], 
       web: { 
        text: values[1], 
        link: values[2] 
       } 
      } 
     }); 
    }); 
}; 
1

それは約束間の同期の問題のように見えます。もう1つの方法は、実行時間を大幅に短縮するJavaScript呼び出しを行うことです。

browser.executeScript(function() { 
    return [].map.call(document.querySelectorAll('cards > card'), function(card) { 
    return { 
     name: card.querySelector('#name').textContent, 
     web: { 
     text: card.querySelector('#web a').textContent, 
     link: card.querySelector('#web a').getAttribute('href') 
     } 
    }; 
    }); 
}).then(function(result){ 
    console.log(result); 
}); 
関連する問題