Unfortunately a Webdriver IWebElement has a GetAttribute() but not a SetAttribute(). Visual C# Kicks shows us how to extend IWebElement with a SetAttribute method:
public static void SetAttribute(this IWebElement element, string attributeName, string value)
{
IWrapsDriver wrappedElement = element as IWrapsDriver;
if (wrappedElement == null)
throw new ArgumentException("element", "Element must wrap a web driver");
IWebDriver driver = wrappedElement.WrappedDriver;
IJavaScriptExecutor javascript = driver as IJavaScriptExecutor;
if (javascript == null)
throw new ArgumentException("element", "Element must wrap a web driver that supports javascript execution");
javascript.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2])", element, attributeName, value);
}
But how do you turn that into a highlight?
First, a couple of Click() methods in your base test class:
public void Click(string elementId)
{
Click(By.Id(elementId));
}
public void Click(By by)
{
IWebElement element = _driver.FindElement(by);
element.Highlight();
element.Click();
}
so we can click on elements a little more simply:
Click("some_id");
instead ofDriver.FindElement(By.Id("some_id")).Click();
andClick(By.CssSelector("#mainContentContainer_someIdString > span"));
instead ofDriver.FindElement(By.CssSelector("#mainContentContainer_someIdString > span")).Click();
Now in my Click() method you can see element.Highlight(); which is an extention in addition to the SetAttribute() above:
public static void Highlight(this IWebElement element)
{
const int wait = 150;
string orig = element.GetAttribute("style");
SetAttribute(element, "style", "color: yellow; border: 10px solid yellow; background-color: black;");
Thread.Sleep(wait);
SetAttribute(element, "style", "color: black; border: 10px solid black; background-color: yellow;");
Thread.Sleep(wait);
SetAttribute(element, "style", "color: yellow; border: 10px solid yellow; background-color: black;");
Thread.Sleep(wait);
SetAttribute(element, "style", "color: black; border: 10px solid black; background-color: yellow;");
Thread.Sleep(wait);
SetAttribute(element, "style", orig);
}
I've just used some plain garish black and yellow so I can spot the change quickly as the tests fly by! Now each element will flash a few times as it is "clicked" by the web test!
0 comments:
Post a Comment