How to select an option in the protractorjs e2e dropdown tests

I am trying to select a parameter from the drop-down list for angular e2e tests using a protractor.

Here is the code snippet for the selection option:

<select id="locregion" class="create_select ng-pristine ng-invalid ng-invalid-required" required="" ng-disabled="organization.id !== undefined" ng-options="o.id as o.name for o in organizations" ng-model="organization.parent_id"> <option value="?" selected="selected"></option> <option value="0">Ranjans Mobile Testing</option> <option value="1">BeaverBox Testing</option> <option value="2">BadgerBox</option> <option value="3">CritterCase</option> <option value="4">BoxLox</option> <option value="5">BooBoBum</option> </select> 

I tried:

 ptor.findElement(protractor.By.css('select option:1')).click(); 

This gives me the following error:

Invalid or invalid string specified. Build information: version: '2.35.0', version: 'c916b9d', time: '2013-08-12 15:42:01' System information: os.name: "Mac OS X", os.arch: ' x86_64 ', os.version: '10 .9', java.version: '1.6.0_65' Driver Information: driver.version: unknown

I also tried:

 ptor.findElement(protractor.By.xpath('/html/body/div[2]/div/div[4]/div/div/div/div[3]/ng-include/div/div[2]/div/div/organization-form/form/div[2]/select/option[3]')).click(); 

This gives me the following error:

ElementNotVisibleError: the element is currently not visible and therefore cannot interact with the Duration of the command or timeout: 9 milliseconds Assembly information: version: '2.35.0', version: 'c916b9d', time: '2013-08-12 15 : 42: 01 'System information: os.name:' Mac OS X ', os.arch:' x86_64 ', os.version: '10 .9', java.version: '1.6.0_65' Session ID: bdeb8088-d8ad- 0f49-aad9-82201c45c63f Driver Information: org.openqa.selenium.firefox.FirefoxDriver Features [{platform = MAC, acceptSslCerts = true, javascriptEnabled = true, browserName = firefox, rotatable = false, locationContextEnabled = true, version = 24.0 = true, databaseEnabled = true, handlesAlerts = true, browserConnectionEnabled = true, nativeEvents = false, webStorageEnabled = true, applic ationCacheEnabled = false, accepts Screenshot = true}]

Can someone help me with this problem or throw some light on what I can do wrong here.

+109
javascript angularjs selenium testing protractor
Oct 25 '13 at 21:08
source share
29 answers

I had a similar problem, and in the end I wrote a helper function that selects outliers.

In the end, I decided that everything was fine with me, choosing the option number, and therefore wrote a method that takes an element and optionNumber and selects this optionNumber. If optionNumber is zero, it does not select anything (leaving the drop-down menu unchecked).

 var selectDropdownbyNum = function ( element, optionNum ) { if (optionNum){ var options = element.all(by.tagName('option')) .then(function(options){ options[optionNum].click(); }); } }; 

I wrote a blog post if you want more information, it also includes checking the text of the selected option in the drop-down list: http://technpol.wordpress.com/2013/12/01/protractor-and-dropdowns-validation/

+78
Dec 01 '13 at 3:05
source share

For me it worked like a charm

 element(by.cssContainingText('option', 'BeaverBox Testing')).click(); 

Hope this helps.

+239
Jun 17 '14 at 8:47
source share

An elegant approach would be to create an abstraction similar to what other selenium language bindings out of the box offer (for example, the Select class in Python or Java).

Let's make a convenient shell and hide the implementation details inside:

 var SelectWrapper = function(selector) { this.webElement = element(selector); }; SelectWrapper.prototype.getOptions = function() { return this.webElement.all(by.tagName('option')); }; SelectWrapper.prototype.getSelectedOptions = function() { return this.webElement.all(by.css('option[selected="selected"]')); }; SelectWrapper.prototype.selectByValue = function(value) { return this.webElement.all(by.css('option[value="' + value + '"]')).click(); }; SelectWrapper.prototype.selectByPartialText = function(text) { return this.webElement.all(by.cssContainingText('option', text)).click(); }; SelectWrapper.prototype.selectByText = function(text) { return this.webElement.all(by.xpath('option[.="' + text + '"]')).click(); }; module.exports = SelectWrapper; 

Usage example (note how readable and easy to use):

 var SelectWrapper = require('select-wrapper'); var mySelect = new SelectWrapper(by.id('locregion')); # select an option by value mySelect.selectByValue('4'); # select by visible text mySelect.selectByText('BoxLox'); 

The solution is taken from the following topic: Select β†’ the abstraction option .




For your information, an object request was created: select β†’ the abstraction option .

+26
Apr 03
source share
 element(by.model('parent_id')).sendKeys('BKN01'); 
+20
Aug 15 '14 at 19:58
source share

To access a specific parameter, you need to specify the nth-child () selector:

 ptor.findElement(protractor.By.css('select option:nth-child(1)')).click(); 
+15
Oct. 25 '13 at 22:07 on
source share

This is how I made my choice.

 function switchType(typeName) { $('.dropdown').element(By.cssContainingText('option', typeName)).click(); }; 
+8
May 26 '14 at 13:43
source share

Here is how I did it:

 $('select').click(); $('select option=["' + optionInputFromFunction + '"]').click(); // This looks useless but it slows down the click event // long enough to register a change in Angular. browser.actions().mouseDown().mouseUp().perform(); 
+5
Apr 29 '14 at 16:24
source share

Try it, it works for me:

 element(by.model('formModel.client')) .all(by.tagName('option')) .get(120) .click(); 
+5
Apr 13 '15 at 9:17
source share

You can try this hope that it will work

 element.all(by.id('locregion')).then(function(selectItem) { expect(selectItem[0].getText()).toEqual('Ranjans Mobile Testing') selectItem[0].click(); //will click on first item selectItem[3].click(); //will click on fourth item }); 
+4
Mar 09 '14 at 12:41
source share

Another way to set an option item:

 var select = element(by.model('organization.parent_id')); select.$('[value="1"]').click(); 
+3
06 Oct '16 at 7:24
source share

We wrote a library that includes 3 ways to select an option:

 selectOption(option: ElementFinder |Locator | string, timeout?: number): Promise<void> selectOptionByIndex(select: ElementFinder | Locator | string, index: number, timeout?: number): Promise<void> selectOptionByText(select: ElementFinder | Locator | string, text: string, timeout?: number): Promise<void> 

An additional feature of these functions is that they wait for the element to be displayed before any select action is performed.

You can find it at npm @ hetznercloud / protractor-test-helper . Types for TypeScript are also provided.

+3
Jun 11 '18 at 10:18
source share

Perhaps not super elegant, but effective:

 function selectOption(modelSelector, index) { for (var i=0; i<index; i++){ element(by.model(modelSelector)).sendKeys("\uE015"); } } 

It just sends the key down the selection you need, in our case we use modelSelector, but obviously you can use any other selector.

Then in my page object model:

 selectMyOption: function (optionNum) { selectOption('myOption', optionNum) } 

And from the test:

 myPage.selectMyOption(1); 
+2
Mar 27 '14 at 5:09
source share

To select elements (parameters) with unique identifiers, for example, here:

 <select ng-model="foo" ng-options="bar as bar.title for bar in bars track by bar.id"> </select> 

I use this:

 element(by.css('[value="' + neededBarId+ '"]')).click(); 
+2
May 19 '15 at
source share

The problem is that solutions that work with regular angular select blocks do not work with angular Material md-select and md-option using protractor. This one was sent to others, but it worked for me, and I can not comment on his message (23 points in total). Also, I cleaned it up a bit, not browser.sleep, I used browser.waitForAngular ();

 element.all(by.css('md-select')).each(function (eachElement, index) { eachElement.click(); // select the <select> browser.waitForAngular(); // wait for the renderings to take effect element(by.css('md-option')).click(); // select the first md-option browser.waitForAngular(); // wait for the renderings to take effect }); 
+2
Jul 29 '15 at 1:27
source share

There's a problem with choosing options in Firefox that the Droogans hack fixes, which I want to mention explicitly here, hoping that this can save someone a specific problem: https://github.com/angular/protractor/issues/480 .

Even if your tests pass locally with Firefox, you may find that they fail in CircleCI or TravisCI or that you use to deploy CI, and recognizing this problem from the very beginning could save me a lot of time :)

+1
Jul 17 '15 at 9:28
source share

Helper for setting the option element:

 selectDropDownByText:function(optionValue) { element(by.cssContainingText('option', optionValue)).click(); //optionValue: dropDownOption } 
+1
Dec 30 '16 at 18:49
source share

If the drop-down menu is below -

  <select ng-model="operator"> <option value="name">Addition</option> <option value="age">Division</option> </select> 

Then the protractorjs code could be -

  var operators=element(by.model('operator')); operators.$('[value=Addition]').click(); 

Source- https://github.com/angular/protractor/issues/600

+1
Feb 26 '17 at 10:19
source share

Select an option by index:

 var selectDropdownElement= element(by.id('select-dropdown')); selectDropdownElement.all(by.tagName('option')) .then(function (options) { options[0].click(); }); 
+1
Apr 17 '17 at 15:17
source share

We wanted to use an elegant solution there using angularjs material, but it did not work, because in the DOM there are actually no option tags / md options until the md-select button is pressed. So the β€œelegant” way didn’t work for us (pay attention to the angular material!) Here is what we did for this, I don’t know if it is the best, but it definitely works now

 element.all(by.css('md-select')).each(function (eachElement, index) { eachElement.click(); // select the <select> browser.driver.sleep(500); // wait for the renderings to take effect element(by.css('md-option')).click(); // select the first md-option browser.driver.sleep(500); // wait for the renderings to take effect }); 

We had to select 4 choices, and while the choice was open, an inscription appeared on the screen to select the next choice. therefore, we need to wait 500 ms to make sure that we are not faced with the problem of material effects that are still in action.

0
Mar 05 '15 at 13:59 on
source share

Another way to set an option item:

 var setOption = function(optionToSelect) { var select = element(by.id('locregion')); select.click(); select.all(by.tagName('option')).filter(function(elem, index) { return elem.getText().then(function(text) { return text === optionToSelect; }); }).then(function(filteredElements){ filteredElements[0].click(); }); }; // using the function setOption('BeaverBox Testing'); 
0
May 22 '15 at 17:18
source share
 ---------- element.all(by.id('locregion')).then(function(Item) { // Item[x] = > // x is [0,1,2,3]element you want to click Item[0].click(); //first item Item[3].click(); // fourth item expect(Item[0].getText()).toEqual('Ranjans Mobile Testing') }); 
0
May 20 '16 at 8:55 a.m.
source share

I poisoned the network for an answer on how to select an option from the drop-down list of the model, and I used this combination, which helped me with the Angular stuff.

element (by.model ("ModelName")). click (). element (By.xpath ('xpath location')). Click ();

It seems that when throwing the code on one line, he could find the item in the drop-down list.

It took a lot of time for this decision. I hope this helps someone.

0
Aug 31 '16 at 11:33
source share

You can select the options for the drop-down list by value: $('#locregion').$('[value="1"]').click();

0
Nov 22 '16 at 11:34
source share

I have slightly improved the solution written by PaulL. First of all, I fixed the code compatible with the latest Protractor API. And then I declare the function in the "onPrepare" section of the Protractor configuration file as a member of the browser instance, so it can be referenced in any e2e specification.

  onPrepare: function() { browser._selectDropdownbyNum = function (element, optionNum) { /* A helper function to select in a dropdown control an option * with specified number. */ return element.all(by.tagName('option')).then( function(options) { options[optionNum].click(); }); }; }, 
0
May 26 '17 at 12:12
source share

Here's how to do it by option value or index . This example is a little rude, but shows how to do what you want:

HTML:

 <mat-form-field id="your-id"> <mat-select> <mat-option [value]="1">1</mat-option> <mat-option [value]="2">2</mat-option> </mat-select> </mat-form-field> 

TS:

 function selectOptionByOptionValue(selectFormFieldElementId, valueToFind) { const formField = element(by.id(selectFormFieldElementId)); formField.click().then(() => { formField.element(by.tagName('mat-select')) .getAttribute('aria-owns').then((optionIdsString: string) => { const optionIds = optionIdsString.split(' '); for (let optionId of optionIds) { const option = element(by.id(optionId)); option.getText().then((text) => { if (text === valueToFind) { option.click(); } }); } }); }); } function selectOptionByOptionIndex(selectFormFieldElementId, index) { const formField = element(by.id(selectFormFieldElementId)); formField.click().then(() => { formField.element(by.tagName('mat-select')) .getAttribute('aria-owns').then((optionIdsString: string) => { const optionIds = optionIdsString.split(' '); const optionId = optionIds[index]; const option = element(by.id(optionId)); option.click(); }); }); } selectOptionByOptionValue('your-id', '1'); //selects first option selectOptionByOptionIndex('your-id', 1); //selects second option 
0
Aug 27 '18 at 9:52
source share
 static selectDropdownValue(dropDownLocator,dropDownListLocator,dropDownValue){ let ListVal =''; WebLibraryUtils.getElement('xpath',dropDownLocator).click() WebLibraryUtils.getElements('xpath',dropDownListLocator).then(function(selectItem){ if(selectItem.length>0) { for( let i =0;i<=selectItem.length;i++) { if(selectItem[i]==dropDownValue) { console.log(selectItem[i]) selectItem[i].click(); } } } }) } 
0
Dec 06 '18 at 10:31
source share

How to choose an option in the js e2e protractor dropdown test. Can anyone help me here.

Afghanistan India

0
Dec 12 '18 at 5:23
source share

Select an option using the CSS property

 element(by.model("organization.parent_id")).element(by.css("[value='1']")).click(); 

or

 element(by.css("#locregion")).element(by.css("[value='1']")).click(); 

If locregion (id), organization.parent_id (model name) are attributes of the selected item.

-one
Oct. 20 '17 at 8:01
source share

You can select the dropdown options, for example:

 element(by.xpath( '//*[@id="locregion"]//option[contains(text(),"Ranjans Mobile Testing")]' )).click(); 
-one
Nov 02 '17 at 4:58
source share



All Articles