Image CAPTCHA
Enter the characters shown in the image.

You are here

WebDriver vs Select2

Nowadays it's quite popular to use Select2 control instead of a common one. Second version has some cool features like filtering, tagging, themes support, etc. On the other hand, sometimes it's quite hard to automate interaction with such controls due to their dynamic nature.

So what challenges do we face, while trying to access Select2 via WebDriver? First of all, we can't use existing Select wrapper to control this component anymore. The other problem is dynamic filtering: as sendKeys prints text character by character, Select2 will be constantly updating its state during typing. Besides that, we can't predict list items' loading time, as it's very dependent from collection size and performance.

We could try to play with WebDriverWait to resolve potential issues, but to be honest there're plenty of factors, which may produce an unexpected result. It's quite hard to control this component even with explicit waits technique. So how we could sort it out?

In this article I'll show how to create a custom Select2 wrapper, which will use its native API for further interaction.

We'll apply an existing template from one of my previous articles to avoid re-inventing the wheel. But first, let's take a look at Select2 native API, which we could use in our wrapper's implementation.

This is a common Select2 structure. As you can see, old select control with options' list is located below the main component. It's usually hidden. Options' values may differ from displayed text. So ideally, it'd be nice to get some option's value by visible text first. And then ask Select2 to display it.

Let's play with browser console first. Assuming that we want to select Monday from dropdown, we need to retrieve option's value, which is equal m first.

As you can see, it could be done via pure jQuery syntax.

So how we could ask Select2 to display an option, which has m value? There's a special function select2, which allows to specify different native actions like openvaldata, etc. It allows us to pass option's value directly to Select2 control for displaying Monday.

Technically, it's everything we need to reach our initial goal. Let's create Select2 wrapper now.

public class Select2 extends HTMLElement {

 

 public Select2(final WebDriver driver, final SearchBy elementSearchCriteria, final String elementValue) {

  super(driver, elementSearchCriteria, elementValue);

 }

 

 public void selectByVisibleText(final String text) {

  executeJS("var value = $(\"" + getElementValue() + "+select\").find('option:contains(\"" + text + "\")').val();" +

    "$(\"" + getElementValue() + "\").select2(\"val\", value);");

 }

 

 public String getSelectedText() {

  return (String) executeJS("return $(\"" + getElementValue() + "\").select2('data').text;");

 }

}

We're calling JavascriptExecutor internally to apply scenario we've already played with in browser console before. Our wrapper extends HTMLElement to allow using custom component directly in PageObjects without explicit initialization.

public class HomePage extends BasePage {

 

 @HTML(searchBy = CSS_SELECTOR, value = "div")

 private Select2 listBoxWeekDay;

 

 public HomePage selectWeekDay(final String day) {

  listBoxWeekDay.selectByVisibleText(day);

  return this;

 }

 

 public String getSelectedWeekDay() {

  return listBoxWeekDay.getSelectedText();

 }

}

 

1

2

3

4

5

6

7

8

9

10

public class Select2Tests extends BaseTest implements PageObjectsSupplier {

 

 @Test

 public void selectValidWeekDay() {

  loadUrl("http://www.bootstrap4xpages.com/bs4xp/demos.nsf/Bootstrap_Select2Listbox.xsp")

    .selectWeekDay("Monday");

 

  Assert.assertEquals("Monday", homePage().getSelectedWeekDay());

 }

}

Hope it'll help you to forget about StaleElementReferenceException, while working with WebDriver and Select2. You can find sources as usual on GitHub.

 

About The Author: 

Copy by permission of Important article, see reference link


 

Displaying 1 - 15 of 123
Title Company Scope Application Rights User Interface Available Supported Technologies Maturity
JMeter Apache Test Automation Framework; Testing Tool Free Use; Opensource Batch Mode; Plugin; Stand Alone application JDBC Driver; JMS; LDAP CORBA; IMAP; POP3; SMTP; SOAP; Web; HTTP; HTTPS 1,999
QA Wizard Pro Seapine Software Testing Tool Commercial; Demo; Floating license; Static license; Trial; User license GUI usability; Remote Control; Remote Execution Adobe Flash; Adobe Flex; AJAX; Dot.NET; Java; Qt; Silverlight; VB App; Web; HTML; HTML5; JavaScript; Windows GUI/Forms; Win32 2,007
JSystem Top-Q Test Automation Framework; Testing Tool Free Use; Opensource Ant Integration; Batch Mode; GUI usability; Integrated into ALM; Integrated into IDE; Maven Integration; Plugin; Stand Alone application Web 2,011
Jelly Apache Test Automation Framework; Testing Tool Free Use; Opensource Batch Mode; JRE UI 2,010
Watir Watir.com Test Automation Framework; Testing Tool Free Use; Opensource Batch Mode; Command Line; GUI usability; Tool Extension RubyOnRails; Web 2,011
FitNesse GitHub project Test Automation Framework; Testing Tool Free Use; Opensource Batch Mode; Integrated into IDE; Plugin; Web based Database; MS SQL; MySQL; Oracle; SOAP; Swing; Web; HTML 2,009
Automation Anywhere Enterprise Automation Anywhere Testing Tool; Testing Utility; Automate Gui Commercial; Demo; Trial GUI usability; Stand Alone application 2,008
Unified Functional Testing Hewlett Packard Enterprise Test Automation Framework; Testing Tool Commercial; Demo; Free Use; Trial Batch Mode; COM API; GUI usability; Integrated into ALM; Remote Execution; Stand Alone application Adobe Flex; OCR; SAP; SAP Gui; Siebel; HTML; Windows GUI/Forms; Win32 2,000
eggPlant Functional TestPlant Monitoring Tool; Testing Tool; Emulator Commercial; Demo; Floating license; Static license; Subscription; Trial GUI usability; Integrated into ALM; Plugin; Remote Execution; Stand Alone application Adobe Flash; Adobe Flex; AJAX; Dot.NET; Java App; Java GUI; Image Verification; Mobile Applications; Android apps; Blackberry apps; Hybrid Apps; iPhone apps; Native Apps; Symbian apps; Web Apps; Windows Mobile apps; Mobile Features; RIA; Silverlight; Swing; Web; DHTML; HTML; SWT; Windows GUI/Forms 2,008
TestComplete SmartBear Software Test Automation Framework; Testing Tool Commercial; Floating license; Trial; User license COM API; Stand Alone application Adobe Air; Adobe Flash; Adobe Flex; C/C++; Dot.NET; Java; Java App; JavaFX; Delphi App; Microsoft Visual FoxPro; PowerBuilder; NTLM; Qt; RIA; Silverlight; VB App; Web; ASP; HTML; Windows GUI/Forms; Win32; WPF/XAML; XBAP 1,999
Tellurium (aost) Google Code Projects Test Automation Framework; Testing Tool Free Use; Opensource Ant Integration; Direct UI; Maven Integration; Plugin JavaScript; jQuery; Xpath 2,007
LDTP GitHub project Test Automation Framework; Testing Tool Free Use; Opensource GUI usability; Stand Alone application Java; Perl App; RubyOnRails 2,004
Ranorex Integrated Test Automation Tools Ranorex Test Automation Framework; Testing Tool; Testing Utility Commercial; Demo; Floating license; Static license; Trial Command Line; GUI usability; Integrated into IDE; Stand Alone application Adobe Air; Adobe Flash; Adobe Flex; AJAX; Dot.NET; Java; Java App; Java GUI; Java SWT; JavaFX; ComponentOne controls; Delphi App; Echo; Ext.Net; GWT; Image Verification; Infragistics; JSON; Microsoft Visual FoxPro; Mobile Applications; Android apps; Hybrid Apps; iPhone apps; Native Apps; Web Apps; Windows Mobile apps; Mobile Features; GPS testing; Mobile Bluetooth; Android; IOS; MochiKit; PowerBuilder; Qt; RIA; SAP; Sencha Touch; Silverlight; SmartClient; VB App; Web; DHTML; DHTMLX; HTML; HTML5; JavaScript; jQuery; Web2.0; Xpath; Windows GUI/Forms; ActiveX; MFC; Win32; Windows 10 Apps; WPF/XAML; YUI; ZK 2,007
Rational Functional Tester [RFT] IBM Rational Test Automation Framework; Testing Tool Commercial; Demo; Static license; Trial GUI usability; Integrated into ALM; Integrated into IDE; Stand Alone application Adobe Flex; AJAX; Code Testing; Dot.NET; Java; Java App; Java GUI; PowerBuilder; SAP; Siebel; Terminal Emulator 3270; Terminal Emulator 5250; VB App; Web; HTML; Windows GUI/Forms; MFC; MSExcel; MSOutlook; Windows 10 Apps 2,001
IQ Bot Automation Anywhere Testing Tool Commercial; Demo; Trial; User license Command Line; GUI usability Adobe Flex; AJAX; C/C++; Dot.NET; Java; Java App; Delphi App; Perl App; PHP; Silverlight; Web; HTML; Windows GUI/Forms; Win32; WPF/XAML 2,012

Pages

MANUFACTURERS Wallboard

Testing tool manufacturers world-wide list
10Levels ABID CONSULTING AccelQ Accord Software ActiMind AdaCore
AdaLog AgileLoad AgileWay Agitar Algorismi ALL4TEC
Andreas Kleffel Android Apache Apica Apollo Systems AppAssist.mobi
Applitools AppPerfect Appsee ApTest Assertible Assure
Atlassian AutoIt Consulti .. Automation Anyw .. Automation Cons .. Axosoft Aztaz Software
Backtrace I/O Badboy BlazeMeter Borvid BrowserStack BSQUARE
BStriker Intern .. CA Technologies Canonical Canoo Engineeri .. Catch Software CelestialTeapot
Chris Mallett Cleanscape ClicTest CloudQA Codeborne CodeCentrix
CodePlex projec .. Codoid Cogitek Compuware Configure IT Conflair
ConSol Core Services Coronys Ltd Countersoft CresTech Softwa .. CrossBrowserTes ..
Crosscheck Netw .. Crowdsourced Te .. Cucumber Ltd Cyara Cygnet Infotech DareBoost
Databene Datamatics Glob .. DevExpress DTM soft Dynatrace LLC EasyQA
Eclipse EkaTechserv Elvior Emmanuel Jorge Empirix EPAM Systems
Equafy Esterel Technol .. eXept Software .. Experitest Finaris Froglogic
FrontEndART Ltd GeneXus GitHub project gnoso Google Code Pro .. GrammaTech
Gurock Software HelpSystems HENIX Hewlett Packard .. Hexawise High-Tech Bridg ..
Hiptest Hitex IBM Rational imbus Shanghai Impetus Inflectra
informUp InTENSO - IT Ex .. Ipswitch Jamo Solutions Janova JAR Technologie ..
JBoss Developer jClarity Jellly.io JetBrains Jively jQuery foundati ..
JS Foundation Jspresso Kanoah KMS Technology Kualitee LDRA Limited
Litmus LoadFocus Loadster Perfor .. MarathonITE Marketcircle Marketcircle
Maveryx Meliora Ltd Micro Focus Sof .. Microsoft Mobile Labs Mobile1st
Mockaroo, LLC Monkop Mozila MSys Technologi .. Navicat NeoTys
Neowise Softwar .. NetCart NORIZZK.COM Novosync Mobili .. NRG Global NTT Resonant
OC Systems Odin Technology OpCord Oracle Orcanos Original Softwa ..
OW2 PANAYA Parasoft PassMark Patterson Consu .. Perfecto Mobile
Pivotal, Inc. Plutora Postman (API To .. PractiTest PrimaTest Process One
Programming Res .. Psoda PureLoad PushToTest Python Q-Assurance
QA Systems QACube QASymphony QAWorks QMetry Quali
Qualitia Softwa .. Quality First S .. Quotium RadView Softwar .. Ranorex RedLine13
Reflective Solu .. ReQtest RevDeBug Robotium Tech Rogue Wave Soft .. Rommana Softwar ..
RTTS ruby-doc.org Runscope Sandklef GNU La .. Sauce Labs Seapine Softwar ..
SeleniumHQ Sencha Sensiple Siemens PLM Sof .. SmartBear Softw .. SmarteSoft
SOASTA SoftLogica Softomotive Softsmith Solution-Soft SonarSource
Sourceforge Spirent Technol .. SQS Software Qu .. Square Stimulus Techno .. Swifting AB
Synopsys T-komp T-Plan TechExcel TechTalk Telerik By Prog ..
Tellurium Test Collab Test Goat Test Recon TestCaseLab testCloud.de Gm ..
TestCraft Techn .. Testenium Testim.io TestingBot TestLodge Testmunk
Testomato TestOptimal TestPlant TestPro Testsigma Techn .. Testuff
The Core Bankin .. The MathWorks The Open Group thePHP.cc Thoughtbot Thoughtworks
Tigris.org Time Simulator Top-Q Trace Technolog .. TrendIC TRICENTIS
Tritusa Pty Ltd TWD Solutions P .. TypeMock Tyto Software Ubertesters UniTESK
Universal Test .. Usetrace Ltd Utrecht Univers .. Validata Group Vanamco AG Vector Software
Veracode Verifaya Corpor .. Verit VersionOne Viewlike.us Vornex Inc.
Watir.com WcfStorm Soluti .. We Are Mammoth Web Performance .. Wintask Wireshark Found ..
Worksoft Xceptance XK72 Xpand IT XQual ZAPTEST
Zeenyx Software .. Zephyr Zeta Software zutubi pty

Theme by Danetsoft and Danang Probo Sayekti