Node.js: 为什么我的期望值没有在 'try-catch' 子句的 'catch' 块中返回?

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

我有一个测试网站功能的 Node.js 项目。它利用 Webdriver.io v4 和 Mocha/Chai.

我创建了一个函数来检查页面上是否存在元素,超时为 1 分钟。如果该元素存在,它应该 return true。如果没有,它应该 return false.

我使用相同的函数来测试页面上是否不存在某个元素。在这种情况下,我期望函数为 return false。但是,该函数没有 returning false,而是抛出超时错误并且 return 既没有 true 也没有 false。这很奇怪,因为我在 try-catch 子句的 catch 块中包含了一个 return false 语句。

在这个项目中,当一个函数失败时,我会得到一个消息,例如expected false to equal trueexpected undefined to equal true。在这种情况下,我收到消息 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.

是的,我希望 element.waitForExist() 抛出一个超时错误,但这个错误应该在 catch 块中通过 returning false 处理。该程序确实显示了 console.log(ex) 行预期的错误日志,但没有 return false.

在这种情况下,为什么我的函数没有 returning false? best/easiest 到 return 正确值的方法是什么?谢谢!

这是我的功能:

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

预期:如果页面上存在元素,函数 returns true。如果该元素在页面上不存在,函数 returns false.

实际:如果页面上存在元素,函数returns true。如果该元素在页面上不存在,则会引发超时错误,但 truefalse 都不会被 returned.

如果您仍然遇到值未被 returned 的问题,请尝试以下方法。我不确定为什么 catch 无法 return,但你能试试下面的方法吗:

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