Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an element doesnt exist selenium nodejs

I want to check if an element exists on the page(which shouldnt) and continue if it doesnt.

driver.wait(function() {   
        fieldBool = driver.isElementPresent(webdriver.By.id("someId"));
        return fieldBool;
}, timeout).then(function(b) {
        assert.equal(false, b, "message");    
});

I want fieldBool to be false, but the test stops(timeout or no such element exists).

like image 689
maddiemadan Avatar asked Oct 15 '25 08:10

maddiemadan


2 Answers

The WebDriver will throw an error when an element does not exist. So, we have to check for the NoSuchElementError.

We can check that an element does not exist by making use of the optional callbacks for the .findElement promise driver.findElement(...).then(successCallback,errorCallback) which will get called as the parameter names imply.

The following is how I've been doing it:

var existed = await driver.findElement(webdriver.By.id("someId")).then(function() {
    return true;//it was found
}, function(err) {
    if (err instanceof webdriver.error.NoSuchElementError) {
        return false;//element did not exist
    } else {
        webdriver.promise.rejected(err);//some other error...
    }
});
assert.equal(existed,false,"message");
like image 108
Arthur Weborg Avatar answered Oct 17 '25 02:10

Arthur Weborg


driver.findElements(webdriver.By.id('someId')).then((elements)=>{
   if(elements.length > 0){
     throw new Error('The Element was found!');
   } else {
     return true;
   }
});

This works by finding all of the elements that match the id, css, name etc, and making sure that the result that comes back (which would be an array of elements) has a length of 0 - meaning no elements were found with that css/id/name etc on the page.

like image 39
KyleFairns Avatar answered Oct 17 '25 03:10

KyleFairns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!