javascript - Node.js:为什么我的预期值没有在“try-catch”子句的“catch”块中返回?
问题描述
我有一个测试网站功能的 Node.js 项目。它利用 Webdriver.io v4 和 Mocha/Chai。
我创建了一个函数来检查页面上是否存在超时 1 分钟的元素。如果元素存在,它应该返回true
. 如果没有,它应该返回false
。
我使用相同的函数来测试页面上是否不存在元素。在这种情况下,我期望函数返回false
。但是,该函数不会返回 false,而是会引发 Timeout 错误并且不返回true
or false
。这很奇怪,因为我在return false
try-catch 子句的 catch 块中包含了一个语句。
在这个项目中,当一个函数失败时,我会得到一个消息,比如expected false to equal true
or 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
返回。
解决方案
如果您仍然存在价值无法退回的问题,请尝试以下方法。我不确定为什么catch
无法返回,但请您尝试以下方法:
checkElementExists: {
value: function (element) {
let val = false;
try {
element.waitForExist();
if (element.isExisting()) {
val = true;
}
} catch (ex) {
console.log(ex);
}
return val;
}
}
推荐阅读
- java - 使用 spring-kafka-test 中的 @EmbeddedKafka 测试监听器
- c# - 如何获取 List 中项目的所有属性并使用 LINQ 将它们转换为 GridColumn?
- python - 在发生此 Keras/TensorFlow CPU 错误后,我的代码是否仍在运行?
- css - 在 Selenium 中验证大小和坐标
- mysql - 应用程序无法启动 :::“无法配置数据源:未指定 'url' 属性,并且无法配置嵌入式数据源。”
- html - 增加Firefox中内容的高度
- java - 如何将(Object obj)这种类型的对象转换为 JSON 然后返回?
- json - 使用 jq 从 gpsd 输出计算使用和查看的卫星数量
- vue.js - :键在 v-for 上重新渲染列表中的一行 || 复合值作为 :key 而不是索引
- ibm-doors - 我们如何对 DOORS 中的视图进行排序