Search code examples
javascriptnode.jsreturntry-catchwebdriver-io

Node.js: Why is my expected value not returned in 'catch' block of 'try-catch' clause?


I have a Node.js project which tests the functionality of a website. It utilizes Webdriver.io v4 and Mocha/Chai.

I've created a function that checks if an element exists on a page with a timeout of 1 minute. If the element exists, it should return true. If it does not, it should return false.

I use the same function to test if an element is NOT present on the page. In this case, I am expecting the function to return false. However, instead of returning false, the function throws a Timeout error and returns neither true or false. This is strange because I've included a return false statement in the catch block of my try-catch clause.

In this project, when a function fails, I will get a message such as expected false to equal true or expected undefined to equal true. In this case, I get the message Timeout of 60000ms exceeded. Try to reduce the run time or increase your timeout for test specs (http://webdriver.io/guide/testrunner/timeouts.html); if returning a Promise, ensure it resolves.

Yes, I am expecting the element.waitForExist() to throw a Timeout error, but this error should be handled in the catch block by returning false. The program does display the error log as expected by the console.log(ex) line, but does not return false.

Why is my function not returning false in this case? What would be the best/easiest way to return the correct value? Thank you!

This is my function:

checkElementExists: {
        value: function (element) {
            try {
                element.waitForExist();
                if (element.isExisting()) {
                    return true;
                } else {
                    return false;
                }
            } catch (ex) {
                console.log(ex);
                return false;
            }
        }
    }

Expected: If element exists on page, the function returns true. If the element does not exist on the page, the function returns false.

Actual: If element exists on page, the function returns true. If the element does not exist on the page, a Timeout error is thrown but neither true or false is returned.


Solution

  • If you still have the problem of value not being returned, please try the below approach. I am not sure why catch fails to return, but could you please try the below:

    checkElementExists: {
        value: function (element) {
            let val = false;
            try {
                element.waitForExist();
                if (element.isExisting()) {
                    val = true;
                } 
            } catch (ex) {
                console.log(ex);
            }
            return val;
        }
    }