Need help on try-catch

I am trying to use a try-catch block in my protractor test, see the code below:

try { element(by.id('usernameas')).sendKeys(data); } catch(err) { console.log('error occured'); } 

I intentionally pass the wrong locator to check if it goes to catch catch or not, currently it gives me a NoSuchElementError error on the command line, and the test stops, and does not go into the catch block.

Please offer.

+6
source share
2 answers

Calling an element (locator) .sendKeys returns a promise that is either allowed or rejected. The promise is part of the control flow.

Calling an element (locator) by itself does not cause an error, it is a promise that is rejected. If you were unable to find the item, in fact you want your entire test to fail, since scneario cannot be completed.

To get the error message, you can use callbacks as shown below.

Important Note : If you handle the failure of promises yourself, your test will not fail, so you better rebuild it.

 try { element(by.id('usernameas')).sendKeys(data).then(function() { console.log('keys sent successfully'); }, function(err) { console.error('error sending keys ' + err); throw err; }); } catch(err) { console.log('error occured'); } 

Console exit (cut off):

 error sending keys NoSuchElementError: no such element (Session info: chrome=31.0.1650.63) (Driver info: chromedriver=2.8.241075,platform=Windows NT 6.1 S ..... 
+14
source

I recently ran into this problem and noticed that you do not need a try / catch block. In Protractor, you can achieve try / catch, as shown below:

 try { <---------------------------- Traditional TRY/CATCH method loadWebApp(); login(); openUserPreferences(); changePassword(); } catch (err) { console.error( "An error was thrown! " + err); } loadWebApp(). then(login). then(openUserPreferences). then(changePassword). then(null, function(err) { <----------------- PROTRACTOR equivalent of try/catch console.error( "An error was thrown! " + err); }); 

Here is the source where I got this information from: https://code.google.com/p/selenium/wiki/WebDriverJs#Promises
under Value Propagation and Chaining

This way you do not need to explicitly add try / catch.


In other words, the reason this method works is because a promise can either be RESOLVED or REJECTED and in case of a rejected or failed promise, this line [ then(null, function(err) { ... } ] will act as the CATCH block.

Also note that then (null, function (err)) (does NOT accept any callback, only errBack; basically, it means that we don’t care if the promise is allowed, we only care about whether it will work and thus NULL for the callback and function (error) for errBack.
No need to wrap this try / catch, and then throw the error as suggested above with the accepted answer (@Eitan Peer). Hope this helps someone struggling with Transporter like me.

+1
source

All Articles