问题
I have to write a test to verify if an element is NOT clickable under certain circumstances. I'm using the Selenium Webdriver Java library.
I know how to do the opposite thing by utilizing the WebDriverWait
and ExpectedConditions
classes.
new WebDriverWait(element, TIMEOUT).until(ExpectedConditions
.elementToBeClickable(By.cssSelector(LOCATOR)));
but I can't seem to find a way to check the opposite thing.
I've gone through the docs for WebElement
and managed to break down the problem into two simpler cases.
The element is disabled - in this case I can just use
WebElement#isEnabled
and wrap it in a predicate passed toWebDriverWait#until
.new WebDriverWait(driver, TIMEOUT).until(new Predicate<WebDriver>(){ public boolean apply(WebDriver driver) { return !getElement().isEnabled(); } });
In some cases, the element does not do anything on click. I want to take this into account as well. The problem is, the element is not disabled per se. It can be clicked but there is no event registered (usually, there is one but in my case, it's being removed by JavaScript).
The second case still troubles me. Is there any way I can wait for such an event to be unregistered?
回答1:
Your solution for case 1 seems like it should work.
For case 2, you'll probably need to invoke JavaScript on the page from within Selenium to check if the element has any event handlers assigned, I believe the following should do the trick:
new WebDriverWait(driver, TIMEOUT).until(new Predicate<WebDriver>() {
public boolean apply(WebDriver driver) {
return (JavascriptExectutor) driver.executeScript(
"arguments[0].onclick == null;", getElement());
}
});
This should get JS to query the current onClick
event handler assigned to the element passed into the JavascriptExecutor
from the method getElement()
and return true if no handler is assigned.
Not actually tested this beyond a quick fiddle with the JS, but it should be all good.
Update: In newer selenium versions, you should be able to use:
ExpectedConditions.not(ExpectedConditions.elementToBeClickable(By))
来源:https://stackoverflow.com/questions/20699922/how-to-wait-for-an-element-not-to-be-clickable-using-selenium-webdriver