Roy
Roy

Reputation: 910

How to check an element clicked or not - selenium

I am trying to check click functionality by using selenium. Here I'm able to click particular element through test case, but for my test case perspective I need to return whether element clicked or not. If the click happens it should return true otherwise need to return false. This is how I'm doing click operation.

		find(By.xpath("elementpath")).click();

Upvotes: 0

Views: 13164

Answers (4)

MiB
MiB

Reputation: 611

Inspired by the answer from @supputuri, I came up with this Java solution testing with Junit, though the main changes I needed to do was in the JS.

String script = "let clicked = false;"
    + "var btn = arguments[0];"
    + "btn.addEventListener('click', () => {"
    + "window.clicked = true;"//without window failed
    + "});"

I choose an external variable for storing the click result as my button was about to disappear from the dom post-click. I don't think you can request data belonging to a non-existing element. Execute the JS with the previously created JavascriptExecutor (here referred to as "js" ) in order to actually add the listener:

js.executeScript(script, myButton); 

and do the click and retrieve the value:

myButton.click();
Boolean clicking = (Boolean) js.executeScript("return clicked;");
assertTrue(clicking);

Upvotes: 0

Please have a look at below method which would be more reliable and give you desired outcome as it would click only when element becomes clickable & tells whether it was clicked or not.

public static boolean isClicked(WebElement element)
{ 
    try {
        WebDriverWait wait = new WebDriverWait(yourWebDriver, 5);
        wait.until(ExpectedConditions.elementToBeClickable(element));
        element.click();
        return true;
    } catch(Exception e){
        return false;
    }
}

Call this method in your class like - boolean bst = className.isClicked(elementRef);

Upvotes: 1

supputuri
supputuri

Reputation: 14135

You can add a listener to the element and setAttribute as part of javascript. Check the attribute once you click on the element.

Below code will an alert when you click on the element. (implemented in Python- execute_script = javascript execution)

element = driver.find_element_by_xpath("element_xpath")
driver.execute_script("var ele = arguments[0];ele.addEventListener('click', function() {ele.setAttribute('automationTrack','true');});",element)
element.click()
# now check the onclick attribute
print(element.get_attribute("automationTrack"))

output:

true

Upvotes: 6

Nilamber Singh
Nilamber Singh

Reputation: 874

You can have a try-catch block do that for you.

try{
   find(By.xpath("elementpath")).click();
}catch(StaleElementReferenceException e){
   return false;
}
return true;

Upvotes: 0

Related Questions