问题
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