问题
I want to click on item by it's text and not by it's value from dropdown box.
i found this great post : https://coderwall.com/p/tjx5zg but it doesn't work as expected, the search continue forever after match was found and it is not clicking the item,
if someone have better example (a working one) or can fix this code and make it work,
i will apperciate.
This is the code Dan Haller from the post used (all rights reserved to him)
function selectOption(selector, item){
var selectList, desiredOption;
selectList = this.findElement(selector);
selectList.click();
selectList.findElements(protractor.By.tagName('option'))
.then(function findMatchingOption(options){
options.some(function(option){
option.getText().then(function doesOptionMatch(text){
if (item === text){
desiredOption = option;
return true;
}
});
});
})
.then(function clickOption(){
if (desiredOption){
desiredOption.click();
}
});
}
This is a select item function that I can use like this:
var browser = protractor.getInstance();
browser.selectOption = selectOption.bind(browser);
browser.selectOption(protractor.By.id('my-dropdown'), 'My Value');
回答1:
This function selects the 3rd option of your select box.
function selectDropdownByNumber(element, index, milliseconds) {
element.findElements(by.tagName('option'))
.then(function(options) {
options[index].click();
});
if (typeof milliseconds !== 'undefined') {
browser.sleep(milliseconds);
}
}
var mySelect = $('#my-dropdown');
selectDropdownByNumber(mySelect, 2);
More info can be found here - http://qainsight.blogspot.fr/2014/04/select-dropdown-value-in-protractor-js.html
回答2:
This question is similar to: How to select option in drop down protractorjs e2e tests
So long as you're on a recent version of protractor, you can just do:
element(by.cssContainingText('option', 'BeaverBox Testing')).click();
If you want to click by number, you can do:
var selectDropdownbyNum = function ( element, optionNum ) {
if (optionNum){
var options = element.findElements(by.tagName('option'))
.then(function(options){
options[optionNum].click();
});
}
};
回答3:
As you want to select option by value, you can use:
var select = element.one(by.model('selectData'));
select.$('[label="Option 1"]').click();
来源:https://stackoverflow.com/questions/22895281/angularjs-protractor-how-to-select-dropdown-option-based-on-its-text-not-value