How to deal with an item not found exception in Protractor

Just as Selenium webdriver provides various exception handling for Java, is there a way we can achieve the same using Protractor.

If we want to handle an exception not found by an element, then what is the best way to do this with Protractor?

+6
source share
3 answers

Answer this question now in the frequently asked FAQ>

How can I catch errors like ElementNotFound?

WebDriver throws errors when commands cannot be completed - for example. unable to click an element that is hidden by another element. If you need to repeat these steps, try using webdriverjs-retry . If you just wanted to catch a mistake, do it the way it is.

Adapted to your question:

elm.isPresent().then(function(present) { /* no webdriver js errors here */} if (present) { /* element exists */ } else { /* element doesn't exist */ } , function(err) { /* error handling here, ie element doesn't if got ElementNotFound but, eventually and less likely, other issues will fall in here too like NoSuchWindowsError or ElementStaleError etc... */ }); 
+11
source

Kudos to @Leo Gallucci for his adaptation to the OP question:

Today I ran into this problem and was hoping to find a solution of this kind:

 /* Function to check for three possible DOM elements; return the element which exists, and get the text contents. */ this.getMySelector = function(){ if (element(by.css('.mySelector')).isPresent()){ return element(by.css('.mySelector')); } else if (element(by.css('.mySelector2')).isPresent()){ return element(by.css('.mySelector2')); } else{ return element(by.css('.mySelector3')); } } 

however, it always got into the first if() and never checked other conditions. Turns out I needed to bind promises for my script:

 this.getMySelector = function(){ element(by.css('.mySelector')).isPresent().then(function (pres) { if (pres){ defer.fulfill( by.css('.mySelector')).getText() ); } else{ element(by.css('.mySelector2')).isPresent().then(function (pres) { if (pres){ defer.fulfill(..); } } } } } // From calling test-spec.js file getMySelector.then(function(text)){ console.log('Now I got the text ==> ' + text); } 
0
source

Try it, Catch has the following syntax in Protractor. In the code below, you will first find the element using Id 'IdTextBoxCode'. Then the code to enter the code is 'codeTextBox.sendKeys (code);' located in the TRY block. If the code throws an exception (in this case, if the element with the Id 'IdTextBoxCode' is not found), it will go to the catch block and the error handling function.

 browser.driver.findElement(by.id(browser.params.loginPage.IdTextBoxCode)).then(function(codeTextBox) { try { console.log("Entering Code: "+code); codeTextBox.sendKeys(code); } catch(err) { console.log('In catch block'); } }, function(err) { console.info('Code Text Box not displayed on page. Proceeding with default Code'); }); 
-1
source

All Articles