Thursday, March 8, 2012

Locate anything with jQuery in Selenium

One of major issues of automation of XHTML or Ajax based pages is locating the elements which dont have id/name. There is no need for the developers to put them in that way or testers can't go and enforce id/name for all the elements.

First shortcut testers take is XPath locators. Yes, that is easy and can work in any browser, but the pitfall is fragility. A addition of row in that page can make the XPath locator to brake. This issue can be solved by using jQuery's :has and :contains options.

Let see an example,

See the below screenshot,
Code for this html can be found here,

In that, there is no id,name or any other CSS attribute to locate expect that input and a tag.

What is the locator for locating first checkbox?

jQuery(':has(input):contains("AA"):last input')

Locator for EB in the first row if EB and 1EA both has value of EB like the below image?

jQuery(':has(:contains("EB")):contains("AA"):last :contains("EB"):last')

How it works?

:has locates all the elements which have the element we are looking for. Then, first :contains filters out the last td/tr/div/span in which both elements are located. This takes out the necessity of juggling with parent,child,adjacent calculations. Once we have the row, it is easy to filter the element we are looking for.

You can locate pretty much anything using these two combinations. Next time, if you think some locator can't located without going for XPath, think again. 

Now, comes the next question, WebDriver aka  Selenium 2 doesn't support jQuery. It only support CSS selectors. How can I use these locators in Selenium? Well, you can inject jQuery into the page using JavaScript executor method. Code for the same can be found elsewhere or look at the Selenium/WebDriver users list. 

Note: You'll notice that, there is no jQuery in the HTML code. I used FireQuery.

Happy Automated Testing.


raja's shared items

My "Testing" Bundle