Thursday, June 30, 2011

WebDriver querying Text Nodes - Lessons learnt

Earlier on today I ran into an odd problem while using WebDriver as part of my ongoing foray into Cucumber as a DSL. I was to trying write automated tests that verified that a link (a tag) had a text node. I could locate the link by an xpath locator.

I can hear you ask why this should be a problem. It was because the link looked as follows:

It turns out the usual WebDriver incantations along the lines of findElement(By.xpath("arbitrary-xpath")).getText() was returning nothing for the link's text. I looked around for a while and found that the only solution I had was to look things up via Javascript seeing as there were no ids to fallback on.

In the end it worked out that document.evaluate became the saviour of the day, since it allowed me to make xpath queries on a document. The result is a java step definition and cucumber feature file that look as follows:

UPDATE: Changed the step definition file so that the xpath lookup is done in WebDriver instead of in the javascript seeing as xpath lookups cannot be relied upon in Internet Explorer.

I suppose you could argue that the html could be changed to be better. True, but atimes that might not be an option. The purists will argue as they do here that it isn't a feature that should be provided by WebDriver but I think it would help to have a way of traversing the DOM once you have looked up an element. I should like to read about other creative solutions to a problem of this nature.