When I’m using selenium to navigate through a web-app, I like to record the session and visually highlight the DOM elements that my testscripts are using.
The IWebDriver
and IWebElement
interfaces don’t supply a method for this….so we’ll have to build our own. The approach I use, is to inject some JavaScript into the webpage to modify the style of the DOM element.
Here’s the code:
public void highlightElement(IWebElement element) { IJavaScriptExecutor js = this.Driver as IJavaScriptExecutor; string OriginalStyle = element.GetAttribute("style"); string HighlightedStyle = OriginalStyle + "border: 3px solid red;"; for (int i = 0; i < 3; i++) { js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);", element, HighlightedStyle); System.Threading.Thread.Sleep(500); js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);", element, OriginalStyle); System.Threading.Thread.Sleep(500); } }
Say for example, that I have the following testscript:
Feature: SeleniumHighlightingOfWebElements I want to show how I can show a user which elements in the DOM my testcases are using Scenario: DemonstrateHighlighting Given I navigate to 'http://en.wikipedia.org/wiki/Hello_world_program' Then there must be a link with 'text' 'computer program' And there must be an element with 'xpath' '//./div[@class='thumbinner' and .//a[@href and normalize-space() = 'Firefox'] ]' And there must be a link with 'text' 'display device' And there must be an element with 'xpath' '//./div[@class='thumbinner' and .//a[@href and normalize-space() = 'CNC'] ]' And there must be a link with 'text' 'programming languages' And there must be an element with 'xpath' '//./div[@class='thumbinner' and .//a[@href and normalize-space() = 'PlayStation Portable'] ]'
That will result in the following screen capture: