In Selenium 2 I want to ensure that an element on the page that the driver has loaded does not exist. I\'m including my naive implementation here.
WebEle
You can retrieve a list of elements by using driver.findElements("Your elements") and then search for the element. if the list doesn't contains the element you got yourself your desired behavior :)
Best solution
protected boolean isElementPresent(WebElement el){
try{
el.isDisplayed();
return true;
}
catch(NoSuchElementException e){
return false;
}
}
If you are testing using junit and that is the only thing you are testing you could make the test expect an exception using
@Test (expected=NoSuchElementException.class)
public void someTest() {
driver.findElement(By.className("commentEdit"));
}
Or you could use the findElements
method that returns an list of elements or an empty list if none are found (does not throw NoSuchElementException
):
...
List<WebElement> deleteLinks = driver.findElements(By.className("commentEdit"));
assertTrue(deleteLinks.isEmpty());
...
or
....
assertTrue(driver.findElements(By.className("commentEdit")).isEmpty());
....
Use assertFalse :)
assertFalse(isElementPresent(By.className("commentEdit")));
If you're using the Javascript API, you can use WebElement.findElements()
. This method will return a Promise with an array of found elements. You can check the length of the array to ensure no items were found.
driver.findElements(By.css('.selector')).then(function(elements) {
expect(elements.length).to.equal(0)
})
I'm using Chai assertion library inside the Promise's callback to expect a certain value.
Reference: https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html
public boolean exist(WebElement el){
try {
el.isDisplayed();
return true;
}catch (NoSuchElementException e){
return false;
}
}
if(exist(By.id("Locator details"))==false)
or
WebElement el= driver.findElementby(By.locator("locator details")
public boolean exists(WebElement el)
try{
if (el!=null){
if (el.isDisplayed()){
return true;
}
}
}catch (NoSuchElementException e){
return false;
}
}