1

I am trying to select an option from a drop-down search box as shown below:

enter image description here

The HTML of the element is below:

<div id="select2-drop-mask" class="select2-drop-mask" style=""></div>
    <div id="select2-drop" class="select2-drop select2-display-none select2-with-searchbox select2-drop-active select2-drop-above" style="left: 130px; width: 707px; top: 338.2px; bottom: auto; display: block;">
        <div class="select2-search">
            <label class="select2-offscreen" for="s2id_autogen1_search">Organization</label>
            <input id="s2id_autogen1_search" class="select2-input" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="combobox" aria-expanded="true" aria-autocomplete="list" aria-owns="select2-results-1" placeholder="" aria-activedescendant="select2-result-label-5" type="text">
        </div>
        <ul id="select2-results-1" class="select2-results" role="listbox">
            <li class="select2-results-dept-0 select2-result select2-result-selectable select2-highlighted" role="presentation">
                <div id="select2-result-label-5" class="select2-result-label" role="option">
                <span class="select2-match"></span>

The code is below:

package com.example.tests;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Dropdown {
  private WebDriver driver;
  private String baseUrl;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @BeforeClass(alwaysRun = true)
  public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "https://xxx.xxxxxxx.com/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void testDropdown() throws Exception {
    driver.get(baseUrl + "/xxxxxxxx/#/login");
    driver.findElement(By.xpath("//input[@type='text']")).clear();
    driver.findElement(By.xpath("//input[@type='text']")).sendKeys("xxxxxxxxx.com");
    driver.findElement(By.xpath("//input[@type='password']")).clear();
    driver.findElement(By.xpath("//input[@type='password']")).sendKeys("t@!L0rUAT");
    driver.findElement(By.cssSelector("button.center-block")).click();
    for (int second = 0;; second++) {
        if (second >= 60) fail("timeout");
        try { if ("".equals(driver.findElement(By.id("headerLogo")).getText())) break; } catch (Exception e) {}
        Thread.sleep(1000);
    }

    driver.findElement(By.linkText("Admin Modules")).click();
    for (int second = 0;; second++) {
        if (second >= 60) fail("timeout");
        try { if (isElementPresent(By.linkText("Role Management"))) break; } catch (Exception e) {}
        Thread.sleep(1000);
    }

    driver.findElement(By.linkText("Role Management")).click();
    for (int second = 0;; second++) {
        if (second >= 60) fail("timeout");
        try { if (isElementPresent(By.xpath("//input[@value='Create New Role +']"))) break; } catch (Exception e) {}
        Thread.sleep(1000);
    }

    driver.findElement(By.xpath("//input[@value='Create New Role +']")).click();
    for (int second = 0;; second++) {
        if (second >= 60) fail("timeout");
        try { if (isElementPresent(By.xpath("//main[@id='content']/div/div/section/div/div/div/div/ul/li/a"))) break; } catch (Exception e) {}
        Thread.sleep(1000);
    }

    driver.findElement(By.id("name")).clear();
    driver.findElement(By.id("name")).sendKeys("Content Creator");
    driver.findElement(By.xpath("//main[@id='content']/div/div/section/div/div/div/div/div[2]/ul/li[2]/button")).click();
    for (int second = 0;; second++) {
        if (second >= 60) fail("timeout");
        try { if (isElementPresent(By.xpath("//main[@id='content']/div/div/section/div/div/div/div/ul/li[2]/a"))) break; } catch (Exception e) {}
        Thread.sleep(1000);
    }

    for (int second = 0;; second++) {
        if (second >= 60) fail("timeout");
        try { if (isElementPresent(By.id("select2-chosen-1"))) break; } catch (Exception e) {}
        Thread.sleep(1000);
    }

    new Select(driver.findElement(By.id("s2id_autogen1_search"))).selectByVisibleText("");
  }

  @AfterClass(alwaysRun = true)
  public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private boolean isAlertPresent() {
    try {
      driver.switchTo().alert();
      return true;
    } catch (NoAlertPresentException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}

I'm getting this error when run the steps using Selenium.

enter image description here

  • 1
    For Angular js Application Why you are using Selenium, Protractor is an another option and you would their speed – Rahul Aug 3 '17 at 5:11
  • It is perfectly fine to use Selenium. – demouser123 Aug 3 '17 at 12:19
1

Refer to the HTML for the drop down,

<label class="select2-offscreen" for="s2id_autogen1_search">Organization</label>
<input id="s2id_autogen1_search" class="select2-input" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="combobox" aria-expanded="true" aria-autocomplete="list" aria-owns="select2-results-1" placeholder="" aria-activedescendant="select2-result-label-5" type="text">
</div>

In HTML, a select class would represent something like this

 <select>
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="mercedes">Mercedes</option>
 <option value="audi">Audi</option>
 </select>

Your code block that you have

new Select(driver.findElement(By.id("s2id_autogen1_search"))).selectByVisibleText("");

would work perfectly fine for the later, since it has a Select tag, but would not work for the first, since it's a plain div and not a Select element as per the HTML.

If your Organisation text appears after clicking on clicking on Choose Organisation then you can do this

driver.findElement(locator for Choose Organisation).clear();  
 //locator can be xpath, id, CSS anything.
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 //wait for the drop down to load.

driver.findElement(By.xpath("//label[contains(text(),"Organization")).click();

0

I faced with same problem and new selenium IDE has option to solve it.

For selecting a value from dropdown (developed using Angular material) it requires two clicks and often scrolling. In first click, rather than to select CSS selector, take xpath (relative) value which would direct to wrapper Ex:

"command": "click",
      "target": "xpath=//div[@id='wrapperIndex']/div/section/div/div/div/dropdown[7]/div/div/md-menu/button/span[2]",

And in second click, again target value using xpath using relative value and not attributes (as in Angular attributes if not defined are dynamic and supposed to change every time and this may lead test failures even it succeed in first instance) second click be targeting value of interest every time Example for second click:

"command": "click",
      "target": "xpath=//div[@id='menu_container_9']/md-menu-content/md-menu-item[15]/button",

For information the path variable in second click defines the position of your selection of interest. For example if a dropdown of colours contains 20 entries and "Red" is at 15th position, above command would select red. But if a new entry is made inside the list and not at the end in a way that position of red changes to 16th in that case it will show error as this command will take value which is at 15th position.

You can avoid this by taking values as input (little complicated)

New contributor
Redefining_QA_Automation is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.