My Top 10 Utility methods I used with Selenium to quickly write Test Cases
My top 10 utility classes that help me most productive in Test Automation Projects.
Having utility methods can help you boost your productivity in your Test Automation Projects by reusing existing codes.
Here are my top 10 methods I often used in different projects with Selenium on C# but you can use it in any of the supported languages.
Wait By CSS Selector
You can use Implicit Wait to wait for an element to be visible. Nevertheless, with highly dynamic pages, each element can differ regarding its visibility. Using Explicit Wait enables you to have more refined control of the expected conditions.
public static void WaitBySelector(IWebDriver driver, string selector)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(selector)));
}
Wait By ClassName
Same as above except through the use of By locator. You can in fact even pass the By type as a parameter.
public static void WaitByClassName(IWebDriver driver, string selector)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName(selector)));
}
Check if Element is Stale
This is a useful method for checking if a method is still present or not. One such popular use case is to determine if a dialog window disappears after the user clicks on the close button.
public static bool CheckElementIsStale(IWebDriver Driver, IWebElement webElement)
{
return StalenessOf(webElement)(Driver);
}
You might in certain cases have to add a try-catch exception so as the swallow it, which can cause the test to unnecessarily fail.
Execute Custom Script
In this example, we’re running a BrowserStack specific command to accept SSL certificates. You can use this method to perform certain actions including sending JavaScript commands.
public static void AcceptSsl(IWebDriver driver)
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"acceptSsl\"}");
}
Wait For Page Load
Compare to other more modern Testing or Automation Frameworks such as Playwright and Puppeteer, Selenium by default doesn’t have a built-in mechanism to wait for the page to load entirely before doing something.
This is however important when dealing with highly dynamic Single Page Applications (SPAs) and the asynchronous nature of modern Web Applications.
public static void WaitPageLoad(IWebDriver driver)
{
new WebDriverWait(driver, TimeSpan.FromSeconds(30)).Until(
d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete")
);
}
Scroll To Bottom
Let’s say you have a web page containing lots of elements and the user needs to scroll down to interact with a particular one. By default, when the page loads, Selenium won’t detect it. Here’s how you can scroll down:
public static void ScrollToBottom(IWebDriver driver)
{
var js = (IJavaScriptExecutor)driver;
js.ExecuteScript("window.scrollBy(0, document.body.scrollHeight)");
}
Scroll Until Element is in View
An even better improvement is to scroll until the element is in view.
IWebElement element = _driver.findElement(By.id("id_of_element"));
((IJavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Get Config
I like using config files JSON or YAML for storing values that are external to the Test Automation System.
Here’s a list:
- DEV, Acceptance or Production URL of the testing Page
- User logging credentials such as Username or Email and Password
- Third-Party credentials such as ClientId (Identity Server)
public static IConfiguration GetConfig()
{
IConfiguration config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
return config;
}
Display Test Name with Date
Unless you’re using Reporting Tools, I find it useful for the test result to display the test name along with the timestamp esp. when finding bugs, errors and debugging tests.
public static string GetTestNameWithDate(string testName)
{
var currentTime = DateTime.Now.ToString("h:mm:ss tt");
return $"{testName} {currentTime}";
}
Detect if Scroll bar is Present
You might want to test for a use case whereby the scrollbar in the browser is displayed or not. I’ve previously used this snippet of code.
public void ScrollbarPresent(IWebDriver driver)
{
string execScript = "return document.documentElement.scrollHeight>document.documentElement.clientHeight;";
IJavaScriptExecutor scrollBarPresent = (IJavaScriptExecutor)driver;
Boolean test = (Boolean)scrollBarPresent.ExecuteScript(execScript);
if (test)
{
Console.WriteLine("Scrollbar is present.");
}
else if (test == false)
{
Console.WriteLine("Scrollbar is not present.");
}
}