Context Menu example-Like Mouse Right Click in web driver API:-
Here we show how to deal with context menu by taking a simple and effective
example. In below example, our first thing that to right click on the element
and the select the required option from the list of values. In this below example
we have switched to an alert to verify that if we have successfully performed clicked
on the required link by using TestNG asserts.
Now in this case, you will need to take the help of WebDriver action class
and perform Right Click action on it. The below is the syntax for this approach
(solution).
Will show how to work with context
menu by taking a simple and good example. Below example, we need to first Right
click on the element and select the required option from the list of values. In
this example we have also switched to an alert to verify that if we have
successfully clicked on the required link by using TestNG
asserts or not.
Now,We need to take the help of WebDriver action class and perform Right Click on
it. The below is the syntax to achieve this goal:
Actions
action = new Actions(driver).contextClick(element);
action.build().perform();
Below are the Steps we have followed
in the below example:
a. Identify an element
b. Wait for the presence of an Element
c. Now perform (right click) Context click
d. After you need to select the required link.
public
class RightClickExampleTest {
WebDriver
driver;
@BeforeClass
public
void Setup() {
driver = new FirefoxDriver();
driver.manage().window().maximize();//
to maximize the browser
}
@Test
public
void mouserightClickTest() {
driver.navigate().to(URL);
By locator = By.cssSelector(".context-menu-one.box");
WebDriverWait wait = new
WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
WebElement
element=driver.findElement(locator);
rightClick(element);
WebElement
elementEdit =driver.findElement(By.cssSelector(".context-menu-item.icon.icon-edit>span"));
elementEdit.click();
Alert
alert=driver.switchTo().alert();
String
textEdit = alert.getText();
Assert.assertEquals(textEdit,
"clicked: edit", "Failed to click on Edit link");
}
public
void mouserightClick(WebElement element) {
try
{
Actions
action = new Actions(driver).contextClick(element);
action.build().perform();
System.out.println("Successfully
Right clicked on the particular element");
}
catch (StaleElementReferenceException e) {
System.out.println("Else-Element
is not attached to the page document "
+
e.getStackTrace());
}
catch (NoSuchElementException e) {
System.out.println("Element
" + element + " was not found in DOM "
+
e.getStackTrace());
}
catch (Exception e) {
System.out.println("Element
" + element + " was not clickable at this moment "
+
e.getStackTrace());
}
@AfterClass
public
void exit() {
driver.quit();
}
}