Reputation: 31
I am trying to select an option "India" from a drop down for the angular e2e tests using protractor.
Here is the code snippet of the select option:
<select id="countryCode" class="form-control nux-select input-md ng-touched ng-dirty ng-valid-parse ng-valid ng-valid-required" required="" data-ng-model="selectedCountry" data-ng-options="c.country for c in country" name="countryCode">
<option class="" selected="" value="">-- select --</option>
<option value="0">Afghanistan</option>
<option value="1">Albania</option>
.
.
.
<option value="29">Brazil</option>
<option value="30">British Indian Ocean Territory</option>
.
.
.
<option value="98">India</option>
<option value="99">Indonesia</option>
I have tried:
element(by.cssContainingText('option', 'India')).click();
But as "British Indian Ocean Territory" option is coming before it is selecting this option instead of "India".
so i tried as below and it works:
element(by.xpath('//select[@id="countryCode"]/option[98]')).click();
but as i'm hard coding and new values may be added into the drop-down can anyone suggest me different way to achieve it.
Upvotes: 3
Views: 587
Reputation: 473763
Other selenium language bindings have select->option
HTML constructions abstracted with a handy Select
class exposing different handy methods, like, for example (python):
select = Select(driver.find_element_by_id('countryCode'))
select.select_by_visible_text('India')
In protractor, there is no such thing built-in, but as kindly proposed by @dmitankin in Select -> option abstraction topic, you can build one and reuse, pretty transparent:
var mySelect = new SelectWrapper(by.id('countryCode'));
mySelect.selectByText('India');
FYI, selectByText()
here is based on xpath expression that checks an option's text:
SelectWrapper.prototype.selectByText = function(text) {
return this.webElement.all(by.xpath('option[.="' + text + '"]')).click();
};
Upvotes: 2
Reputation: 610
element.all(by.cssContainingText('option', 'India')).then(function(items) {
expect(items.length).toBe(2);
expect(items[0].getText()).toBe('British Indian Ocean Territory');
expect(items[1].getText()).toBe('India');
});
I am not sure that it is the best solution, but it should work. It wont be stable only in case if you will add new value which contains 'India', but it does not look realistic.
Upvotes: 0