How to get element presence in Boolean type in Selenium 3 (instead of isElementPresent)

896 Views Asked by At

I am trying to learn automation testing with WebDriverJS-Mocha in NodeJS via guidance of page at below, which the scenario was being coded compatible with Selenium 2(not compatible with Selenium 3): https://watirmelon.blog/2015/10/28/getting-started-with-webdriverjs-mocha/

And, I just want to know how to get element presence in Boolean type in Selenium 3 as it is 'isElementPresent' in Selenium 2

I am using two npm packages:

npm install [email protected]
npm install -g mocha

I am running my js file as below:

mocha spec.js

I tried to code it as below:

driver.findElements(By.id('sampleID')).then(found => true, function(present) {
        driver.wait(until.elementLocated(By.id('sampleID')), 3000);
        assert.equal(present, true, "Quote container not displayed");
    });
2

There are 2 best solutions below

0
On

You can achieve this with below method...

public boolean checkForPresenceOfElementByXpath(String xpath){
    try{
        (new WebDriverWait(driver, 5)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
        //driver.findElement(By.xpath(xpath));
        return true;
    }catch(Exception e){
        return false;
    }
}
0
On

It seems that you should wrap your findElements INSIDE the wait, and not wrap the wait inside the findElements. You first wait until the first element is found and then you find all the elements.

However I also think you can accomplish this with elementLocated by itself.

Instead of:

driver.findElements(By.id('sampleID')).then(function(present) {
    driver.wait(until.elementLocated(By.id('sampleID')), 3000);
    assert.equal(present, true, "Quote container not displayed");
});

Just do

driver.wait(until.elementLocated(By.css('#sampleID')), 3000).then(function(present){
    assert.equal(present, true, "Quote container not displayed");
});

If that doesn't do what you want and you need findELements, do the wait first then do whatever you want with findElements.

driver.wait(until.elementLocated(By.css('#sampleID')), 3000);
driver.findElements(By.css('#sampleID')).then(function(els){
    assert.equal(present, true, "Quote container not displayed");
});