Home > other >  Confirm if button was clicked with Selenium
Confirm if button was clicked with Selenium

Time:08-16

I'm using Selenium to perform some tests with JavaScript, and I have a button that does nothing, there is no redirect or action and I believe that this code is clicking the button:

driver.findElement(By.id("submit")).click()

What I want to know is, how can I confirm whether this button was actually clicked or not? I've been trying to use try catch but not having any luck. I'm new to testing and have been searching for an answer but haven't found anything that works in this scenario.

CodePudding user response:

As you mentioned, normally clicking some button normally causes some action: redirect, open drop list, invoke some dialog etc. It also can cause some element attribute change, maybe that element itself or some other element attribute. So, please check for any of the above. In case there is absolutely no action and no change caused by clicking the button AFAIK you can not validate if that element was clicked or not.

CodePudding user response:

If you really want to verify if it's clickable, you can wait and it will reply, just keep it in a try-catch block if you don't want your program to stop.

int waitTime = 5;
WebDriverWait wait = new WebDriverWait(yourWebDriver, waitTime);
WebElement btnSubmit = driver.findElement(By.id("submit"))
wait.until(ExpectedConditions.elementToBeClickable(btnSubmit));
System.out.println('Button has been clicked');

CodePudding user response:

As per the Specification:

The Element Click command scrolls into view the element if it is not already pointer-interactable, and clicks its in-view center point.

If the element’s center point is obscured by another element, an element click intercepted error is returned. If the element is outside the viewport, an element not interactable error is returned.


This usecase

To confirm if button was clicked you can wrap up the click inducing WebDriverWait for the elementToBeClickable() within a try-catch{} block catching TimeoutException as follows:

try {
  new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.id("submit"))).click();
}
catch(TimeoutException e) {
  System.out.println(e);
}
  • Related