webdriverio Loop through options in select element

孤人 提交于 2019-12-14 03:55:15

问题


Example HTML:

<select id="random_text">
    <option value="option1">asadka_TEST</option>
    <option value="option2">Peter Parker</option>
    <option value="option3">Clark Kent</option>
    <option value="option4">aldkfsd_TEST</option>
</select>

Javascript code in class

class TestPage extends Page {

    get fullNameSelect() {return browser.element('#random_text');}

    iterateAndSelect() {
        this.fullNameSelect.value.ForEach() //pseudo code
    }
}

I want iterateAndSelect function to iterate through all options and select first option that ends with "_TEST".

So far, I've only figured out that there is selectByVisibleText action but the problem is that I want to select option based on condition that value ends with "_TEST" string, and with this action I have to provide the exact value.


回答1:


The simplest way would be to find the index of the first option that ends with _TEST:

const index = browser.getElements('option').findIndex(option => {
    return option.getText().endsWith('_TEST')
});

Then you can select that value by using that index:

browser.getElement('select').selectByIndex(index);



回答2:


Here's a simple way of doing it.

// get all options
const options = document.getElementById('random_text').children
// filter key test options
const tests = Object.keys(options).filter( i => options[i].text.indexOf('_TEST') > 0)
// run tests here
tests.map(i => {
  console.log(options[i].text)
})
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <select id="random_text">
    <option value="option1">asadka_TEST</option>
    <option value="option2">Peter Parker</option>
    <option value="option3">Clark Kent</option>
    <option value="option4">aldkfsd_TEST</option>
  </select>
</body>
</html>



回答3:


Here is Webdriverio code you want to give a try:

class TestPage extends Page {

  get fullNameSelect() {return browser.elements("option");}

  iterateAndSelect() {
       var arr=[];

     this.fullNameSelect.value.forEach(function(elem) {

     var text=browser.elementIdText(elem.ELEMENT).value;
     if(text.endsWith('_TEST')) {
        arr.push(text); 
     }
     console.log(arr); // all texts that ends with _TEST
    });
 }
   }
module.exports = new TestPage();


来源:https://stackoverflow.com/questions/51445577/webdriverio-loop-through-options-in-select-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!