首页 > 解决方案 > Node.js:为什么我的预期值没有在“try-catch”子句的“catch”块中返回?

问题描述

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

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

我使用相同的函数来测试页面上是否不存在元素。在这种情况下,我期望函数返回false。但是,该函数不会返回 false,而是会引发 Timeout 错误并且不返回trueor false。这很奇怪,因为我在return falsetry-catch 子句的 catch 块中包含了一个语句。

在这个项目中,当一个函数失败时,我会得到一个消息,比如expected false to equal trueor expected 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 块中通过返回来处理false。该程序确实按照该行的预期显示错误日志console.log(ex),但不返回false.

为什么false在这种情况下我的函数没有返回?返回正确值的最佳/最简单方法是什么?谢谢!

这是我的功能:

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

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

实际:如果页面上存在元素,则函数返回true. 如果页面上不存在该元素,则会引发 Timeout 错误,但既不返回true也不false返回。

标签: javascriptnode.jsreturntry-catchwebdriver-io

解决方案


如果您仍然存在价值无法退回的问题,请尝试以下方法。我不确定为什么catch无法返回,但请您尝试以下方法:

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

推荐阅读