【问题标题】:If element is not present in NightwatchJS how to stop test without error如果 NightwatchJS 中不存在元素如何停止测试而不出错
【发布时间】:2017-09-18 10:23:24
【问题描述】:

在我的 Nightwatch 测试中,我有一个 before each 运行并从 Facebook 中删除一个应用程序。如果应用程序不存在,我只想停止之前的测试。

.waitForElementPresent('#root div.touchable a', 2000, false, function (result) {
  if (result.value === false) {
    browser.saveScreenshot('./test/e2e/img/element-not-there.png')
    browser.end()
  }
})
.doSomethingIfElementIsThere() // not real ;)

即使设置了false 参数,这似乎也不起作用。我收到此错误:

ERROR: Unable to locate element: "#root div.touchable a" using: css selector
    at Object.before (/Users/user/projects/project/test/e2e/specs/testy-mc-test-face.js:30:8)
 ✖ Timed out while waiting for element <#root div.touchable a> to be present for 2500 milliseconds.  - expected "found" but got: "not found"
    at Object.before (/Users/user/projects/project/test/e2e/specs/testy-mc-test-face.js:30:8)

只是想知道如何检查某些内容而不是错误。或者如果元素存在则继续断言?

感谢水桶

【问题讨论】:

  • 元素是否缺少测试的失败条件?优雅地处理这个问题确实应该是您正在测试的代码的工作,以便测试可以与它交互,而不是测试有选择地不运行测试的责任。

标签: javascript vue.js nightwatch.js e2e-testing


【解决方案1】:

我查了code of the elementPresent assertion

this.command = function(callback) {
  return this.api.elements(this.client.locateStrategy, selector, callback);
};

this.value = function(result) {
  return (result.status !== 0 || result.value.length === 0) ? 'not present' : 'present';
};

它使用low-level api,您可以使用它来测试元素是否存在:

.elements()

在页面上搜索多个元素,从文档根目录开始。定位的元素将作为 WebElement JSON 对象返回。 要传递的第一个参数是定位器策略,在 WebDriver 文档中有详细说明。

我想解决方案可能是这样的:

browser.elements('css selector', '#root div.touchable a', result => {
  const isPresent = result.status === 0 && result.value.length > 0;
  // doStuff
});

【讨论】:

  • 非常感谢,工作就像一种魅力。让我意识到我应该更多地进入源代码。再次感谢
  • 我想你可以验证我的答案:-)
猜你喜欢
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 2020-05-08
  • 2018-07-19
  • 2016-06-26
  • 1970-01-01
相关资源
最近更新 更多