App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide 5 Selenium tricks to make your life easier

5 Selenium tricks to make your life easier

Shreya Bose, Technical Content Writer at BrowserStack -

Chances are that you use Selenium WebDriver as the go-to framework for your web automation needs. It is certainly one of the most popular test automation frameworks in existence. This article has taken the liberty of listing five tricks that you probably didn’t know you could do with your Selenium test cases.

By utilizing the information below, testers will be able to organize tests, monitor execution and generate comprehensive reports with greater ease.

Trick #1 – Launching multiple tests with same parameters

This is for cases in browser automation in which the same values have to be used in diverse tests. Use TestNG capacity to define specific parameters for a test suite in the configuration file.

In the example below, the code is directed to provide the URL for the WebDriver method in order to execute a test suite. The test has been written in the TestNG framework.

public class TestNGParameterExample {
@Parameters({"firstSampleParameter"})
@Test(enabled = true)
public void firstTestForOneParameter(String firstSampleParameter) {
driver.get(firstSampleParameter);
WebElement searchBar = driver.findElement(By.linkText("Mobile Device & Browser Lab"));
searchBar.click();
Assert.assertEquals(driver.findElement(By.tagName("h1")).getText(), "Mobile Device & Browser Lab");
}
@Parameters({"firstSampleParameter"})
@Test
public void secondTestForOneParameter(String firstSampleParameter) {
driver.get(firstSampleParameter);
WebElement searchBar = driver.findElement(By.linkText("Live Cross Browser Testing"));
searchBar.click();
Assert.assertEquals(driver.findElement(By.tagName("h1")).getText(), "Cross Browser Testing");
}
}
testng.xml file structure is shown below.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="Suite1" verbose="1" >
<parameter name="firstSampleParameter" value="https://experitest.com/"/>
<test name="Nopackage" >
<classes>
<class name="TestNGParameterExample" />
</classes>
</test>
</suite>

Remember that all parameterized tests have to be initiated with a builder such as Maven.

Try Selenium Automation Testing for Free

Trick #2 – Passing Simple Values to a Test

In this case, the objective is to create tests that enable the processing of data sets. To do this, use the DataProvider method, which is capable of returning a two-dimensional array of objects.

  1. The first array dimension defines the number of test launches.
  2. The second dimension corresponds to the number and types of test values.

To understand this further, examine the code below which uses the annotation @DataProvider

@DataProvider()
public Object[][] listOfLinks() {
return new Object[][] {
{"Mobile Device & Browser Lab", "Mobile Device & Browser Lab"},
{"Live Cross Browser Testing", "Cross Browser Testing"},
{"Automated Mobile Testing", "Mobile Test Automation!"},
};
}

The code below points to the data provider method that has the corresponding name.

@Test(dataProvider = "listOfLinks")
public void firstTestWithSimpleData(String linkname, String header) {
driver.get("https://experitest.com/");
WebElement searchBar = driver.findElement(By.linkText(linkname));
searchBar.click();
Assert.assertEquals(driver.findElement(By.tagName("h1")).getText(), header);
}

Trick #3 – Handle Pop-up Windows

A common challenge in Selenium web automation is interacting with pop-up windows. These windows appear mainly in three formats:

  1. Simple alert: displays a message
  2. Confirmation alert: requests user to confirm some operation
  3. Prompt alert: informs the user that they need to input some data

While WebDriver cannot handle Windows-based alerts, it can handle web-based alerts. Use the switch_to method to manage pop-ups.

<!DOCTYPE html>
<html>
<body>
<h2>
Demo for Alert</h3>

Clicking below button 
<button onclick="create_alert_dialogue()" name ="submit">Alert Creation</button>
<script>
function create_alert_dialogue() {
alert("Simple alert, please click OK to accept");
}
</script>
</body>
</html>

Displayed below is an instance in which the switch_to method is used. In this case, switch.to.alert is used to switch to the alert pop-up box. Once this happens, the alert is accepted with the alert.accept() method.

from selenium import webdriver
import time
from time import sleep
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from builtins import str

driver = webdriver.Firefox()
driver.get("file://<HTML File location>")

driver.find_element_by_name("submit").click()
sleep(5)

alert = driver.switch_to.alert
text_in_alert = alert.text
print ("The alert message is "+ text_in_alert)
sleep(10)

alert.accept()

print("Alert test is complete")

driver.close()

Test Pop Up on Real Device Cloud for Free

Trick #4 – Handle Dynamic Content

Most present-day websites contain content that is dynamic in nature. This mostly applies to AJAX based apps.

A common example of this is an e-commerce site. Such sites tend to show different products to different users, depending on the user’s location or their previous product choices. When testing a site like this, it is important to ensure that WebDriver continues testing when the entire content of a page has loaded completely.

Elements on dynamic pages often load at different time intervals, issues may arise if an element is not yet present in the DOM. However, this challenge can be resolved quite effectively with the use of Selenium wait commands.

By using Explicit Wait, a tester can direct WebDriver to pause test execution until a certain condition is met. Use it along with the thread.sleep() function if the condition is to wait for an exact period of time.

In the example below, two searches occur on the URL https://www.browserstack.com/. The first search is for the element home-btn. Here, the element is located via CLASS_NAME for a maximum duration of 5 seconds.

The second search looks for a clickable element login for a maximum interval of 5 seconds. If the element is present, a click() action is executed.

Both instances use WebDriverWait along with ExpectedCondition.

from selenium import webdriver
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Firefox()
driver.get("https://www.browserstack.com/")

try:
myElem_1 = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'home-btn')))
#element = driver.find_element_by_partial_link_text("START TESTING")
print("Element 1 found")
myElem_2 = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'login')))
print("Element 2 found")
myElem_2.click()
sleep(10)
#except NoSuchElementException:
except TimeoutException:
print("No element found")

sleep(10)

driver.close()

Trick #5 – Handle Drop-Down Menu

Let’s begin by understanding the basics.

The Select class is used by Selenium WebDriver to select and deselect options in a dropdown. Objects of Select type can be initialized by passing the dropdown WebElement as a parameter to its constructor.

Example:

WebElement testDropDown = driver.findElement(By.id("testingDropdown")); 
Select dropdown = new Select(testDropDown);

There are three ways to select an option from the drop-down menu-

1. selectByIndex – Used to select an option based on its index number, beginning with 0.

dropdown.selectByIndex(5);

2. selectByValue – Used to select an option based on its ‘value’ attribute.

dropdown.selectByValue("Database");

3. selectByVisibleText – Used to select an option based on text over the option.

dropdown.selectByVisibleText("Database Testing");

Try Handling Drop Down using Selenium for Free

Use the techniques described above to make your Selenium tests easier, more organized and less time-consuming. Additionally, it is important to choose a Selenium-based platform that facilitates automated testing. Look out for tools that allow for testing on a real device cloud, such as BrowserStack. As a testing tool, it is designed to make testers’ lives easier, providing developer-centric resources such as in-built dev tools and integrations with popular programming languages and frameworks. Consequently, it makes automated Selenium testing faster, smoother and more result-oriented.

Tags
Automation Testing Selenium Selenium Webdriver

Featured Articles

Selenium Automation Framework: A Detailed Guide

Learn Selenium with Java to run Automated Tests

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.