Protractor - Error Handling in Framework

2019-04-13 16:48发布

问题:

How can we handle error in a Protractor - Cucumber based framework?

There are assert failures, which is a genuine fail and there are errors in javascript code (e.g. - element not found, array is empty, something undefined etc..). I wish to handle the later in a graceful manner.

Currently Protractor tests fail for the said errors but the messages are not friendly and hard to comprehend. They mostly point to location of errors in protractor library files and not where the actual error occurred in the script (file name, line number etc.)

e.g

"NoSuchElementError: No element found using locator: By(css selector, .listContainer li:nth-child(1) span)">NoSuchElementError: No element found using locator: By(css selector, .listContainer li:nth-child(1) span)
    at WebDriverError (node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:27:10)
    at NoSuchElementError (node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:242:10)
    at node_modules\protractor\built\element.js:705:27
    at ManagedPromise.invokeCallback_ (node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:1379:14)
    at TaskQueue.execute_ (node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2913:14)
    at TaskQueue.executeNext_ (node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2896:21)
    at node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2775:27
    at node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:639:7
    at process._tickCallback (node.js:369:9)Error

When I do something like this to handle the error -

return selectAll.click().then(function(){

            }, function(err){
                console.log('error occured..');
                console.log(err);
            });

The error is reported but the test passes. I want it to fail as well as report the error gracefully.

回答1:

You can do this by throwing the error inside your error first callback!

You could do something like this -

return selectAll.click().then(function(){

        }, function(err){
           throw new Error('Error occurred!'); //this would fail the step definition as well
        });