将 WebDriver 与 Backbone.js 一起使用时处理陈旧元素

Dealing with stale elements when using WebDriver with Backbone.js

我们正在使用 Backbone.js 并且在 运行 我们的 WebDriver 测试时遇到问题。我们收到以下错误:

org.openqa.selenium.StaleElementReferenceException: Error Message => 'Element does not exist in cache'

我们的理解是,这是在我们找到一个元素并对该元素执行操作时引起的(例如 click())。我们找到的元素已经消失 'stale',我们怀疑该元素已被重新渲染或修改。

我们看到了很多我们不喜欢的解决方案:

  1. 使用Thread.Sleep(...)。我们不想在我们的代码中显式睡眠
  2. 使用重试策略,作为循环或尝试捕获 StaleElementReferenceException。我们认为这不是 right/clean 解决方案,并且将来很容易崩溃
  3. 有些人正在使用 WebDriverWait 并等待某些 javascript 函数执行 returns true。我们看到人们在 Angular 中等待 notifyWhenNoOutstandingRequests(callback),但找不到任何明显的 Backbone。

我们希望有一个干净的解决方案,不涉及显式休眠或某种形式的循环。有什么想法吗?

我进一步研究了 WebDriverWaits,我想我已经想出了对我们有用的期望组合:

wait.until(refreshed(elementToBeClickable(...)));

refreshed expectation is a wrapper for other expectations that deals with StaleElementReferenceException, and the elementToBeClickable expectation checks the element is clickable. What is interesting is that looking at the source for the built in expectations, some of them deal with StaleElementReferenceExceptions, while others don't (e.g. presenceOfElementLocated) 并且需要包含在刷新的期望中,所以我认为这就是我第一次看到 WebDriverWaits 时最初让我失望的原因。