I am trying to use try-catch block in my protractor test, please see the code below:
try {
element(by.id('usernameas')).sendKeys(data);
}
catch(err) {
console.log('error occured');
}
I am deliberately passing wrong locator to check whether it is going in catch block or not, currently it is giving me error NoSuchElementError
on command prompt and test execution stops rather than going into catch block.
Please suggest.
I ran into this problem recently and noticed that you DONT need the try/catch block. In Protractor, you can achieve the try/catch like following:
Here's the source where I got this info from: https://code.google.com/p/selenium/wiki/WebDriverJs#Promises
under
Value Propagation and Chaining
So again, you don't need to explicitly add a try/catch.
In short, 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 notice that the then(null, function(err))( is NOT taking any callback but only an errBack; so basically, this is saying we don't care about whether the promise gets resolved, we only care about whether it fails and thus the NULL for callback and the function(error) for the errBack.
No need to wrap this in a try/catch then throw the error as suggested above by the accepted answer (@Eitan Peer).
Hope this helps someone out there struggling with Protractor as I did.
The call to element(locator).sendKeys returns a promise which is either resolved or rejected. The promise is part of the test's control flow.
The call to element(locator) itself does not throw an error, it is the promise which is rejected. If you fail to find an element you actually want your entire test to fail, since the scneario cannot be completed.
To get the error message you can use the promise callbacks, as demonstrated below.
Important note: if you handle the promise failure by yourself your test won't fail, so you should better rethrow it
The console output is (trimmed):