簡體   English   中英

如何使用量角器返回數組中的getText()值

[英]How to return the getText() values in array using protractor

我正在嘗試使用以下函數返回列表中存在的選項。

的HTML

<select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
<select>

功能

getValues(){
  var ele = element(by.xpath("......../select"));
  return ele.all(by.tagName('option')).getAttribute('value').getText().then(function (text){
  for (var i = 0; i < text.length; i++) {
    text[i] = text[i].trim();
  }
  return text;
 });        

}

當我使用console.log(getValues())在控制台中打印值時,控制台將顯示ManagedPromise{.....}函數而不是選項。

但是我期望這些選項為["one","two","three"]數組。 誰能幫我?

如果還可以這樣做,為什么還要為其創建復雜的方法

 getValues() { return element.all(by.css('select option')).getText(); } 

getText()也可以在ElementFinderArray上執行,它將返回包含['one', 'two', 'three']

更新:具有修剪功能

首先,由於以下兩個原因,您的代碼無法使用:

  1. 量角器使用承諾,您首先需要解決承諾,然后才能使用值。 另請參閱您之前提出的問題之一
  2. 您正在使用.getAttribute('value').getText() 這將永遠行不通。

您將在下面找到3種不同樣式的工作示例。

 // with your code getValues() { var ele = element(by.xpath("......../select")); return ele.all(by.tagName('option')) .map(function(option) { return option.getText() .then(function(optionText) { return optionText.trim(); }); }); } // with protractor shorthand notation getValues() { return $$('select option').map((option) => { return option.getText() .then((optionText) => { return optionText.trim(); }); }); } // 1 line getValues() { return $$('select option').map((option) => option.getText().then((optionText) => optionText.trim())); } 

最優雅的方法是使用.map() 請參閱文檔

您唯一需要記住的是.map()返回A promise that resolves to an array of values returned by the map function.

<!DOCTYPE html>
<html>
<body>

<select id="sel">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<p>Click the button to display values</p>

<button onclick="clickHandler()">Try it</button>

<p id="demo"></p>  
</body>
<script "text/javacript">
function clickHandler() {
    var options = document.getElementById("sel").childNodes;
    let results =[];
    [].forEach.call(options, function(option) {
      if (option instanceof HTMLOptionElement) {
        results.push(option.text); 
        // Swap for option.value if you like too would be lower case
      }
    });
    document.getElementById("demo").innerHTML = results.toString();
}
</script>
</html>

在這里觀看現場演示
MDN上的HTMLOptionElement

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM