Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Select2 with Selenium webdriver

Tags:

I've been banging my head against the wall trying to select a option from a ajax enabled select2 select list with the selenium webdriver. I've managed to get it working with the IE webdriver but not firefox. Here is my hacky solution for IE

 public static void SetSelect2Option(this IWebDriver driver, By locator, string subContainerClass, string searchTerm, TimeSpan? ajaxWaitTimeSpan = null)     {         var select2Product = driver.FindElement(locator);         select2Product.Click();         var searchBox = driver.FindElement(By.CssSelector(subContainerClass + " .select2-input"));         searchBox.SendKeys(searchTerm);         if (ajaxWaitTimeSpan != null)         {             driver.Manage().Timeouts().ImplicitlyWait(ajaxWaitTimeSpan.Value);         }         var selectedItem = driver.FindElements(By.CssSelector(subContainerClass + " .select2-results li")).First();         selectedItem.Click();         selectedItem.SendKeys(Keys.Enter);     } 

In Firefox, this solution works up until the point of the SendKeys call where it just hangs and moves on to the next step without actually firing select2's events to populate the selected item.

I've also tired using the http://code.google.com/p/selenium/wiki/AdvancedUserInteractions api with similar results.

Has anyone run into a similar issue before?

like image 499
Justen Martin Avatar asked Jul 19 '13 19:07

Justen Martin


1 Answers

Could you please show us the locators as well? Here is what I tested without any issues.

Note

  1. To open select box, use css selector #s2id_e1 .select2-choice, or equivalent XPath.
  2. Make sure #select2-drop is the visible one, by css selector #select2-drop:not([style*='display: none']), or equivalent XPath.
  3. Make sure to click the selectable item using subContainerClass + .select2-results li.select2-result-selectable, or equivalent XPath.
var driver = new FirefoxDriver(); driver.Url = "http://ivaynberg.github.io/select2/";  var select2Product = driver.FindElement(By.CssSelector("#s2id_e1 .select2-choice")); select2Product.Click();  string subContainerClass = "#select2-drop:not([style*='display: none'])"; var searchBox = driver.FindElement(By.CssSelector(subContainerClass + " .select2-input")); searchBox.SendKeys("Ohio");  var selectedItem = driver.FindElements(By.CssSelector(subContainerClass + " .select2-results li.select2-result-selectable")).First(); selectedItem.Click(); 
like image 180
Yi Zeng Avatar answered Oct 04 '22 16:10

Yi Zeng