Nightwatchjs: how to check if element exists without creating an error/failure/exception

Aaron Kuehn picture Aaron Kuehn · Jul 28, 2015 · Viewed 22.9k times · Source

In the page I'm testing, two buttons may be displayed: BASIC or ADVANCED.

I want to be able to tell if the ADVANCED button is showing -- and if so, click it.

If the BASIC button is showing, I want to do nothing and continue with my test.

All of the Nightwatchjs options I've experimented with generate a failure message. For example if I "waitforpresent" or "waitforvisible" and the button is not there, it generates an error/failure. I just want to know which button is present so I can make a decision in my code.

Here is what I have tried:

try { 
    browser.isVisible('#advanced-search', function(result) {console.log(result.state); }) 
} catch (myError) 
{ 
    console.log(myError); 
}

Thoughts?

Answer

EricM picture EricM · Apr 10, 2016

You can achieve this by using the Selenium protocol "element" and a callback function to check the result status to determine if the element was found. For example:

browser.element('css selector', '#advanced-search', function(result){
    if(result.status != -1){
        //Element exists, do something
    } else{
        //Element does not exist, do something else
    }
});