[英]How to resolve StaleElementReference in Mocha.js + Selenium + wd.js
我正在使用Mocha + SeleniumServer + wd.js + chai-as-promised为网站编写自动化测试。 该网站的前端使用JavaScript,当执行某些操作时,该JavaScript似乎会刷新页面上的元素。 即,在选择网格中的元素后,将启用“下一个”按钮,以允许用户继续下一页。 似乎这会更改对按钮元素的引用,从而导致StaleElementReference错误。
describe('1st step', function () {
it('should select an element is grid', function () {
return browser
.waitForElementByCss('#grid', wd.asserters.isDisplayed, 20000)
.elementByCss('#grid .elementToBeSelected')
.click()
.sleep(1000)
.hasElementByCss('#grid elementToBeSelected.active')
.should.eventually.be.true;
});
it('should proceed next step', function () {
return browser
.waitForElementByCss('.btnGrid .btn.nextBtn:not(.disabled)', wd.asserters.isDisplayed, 20000)
.elementByCss('.btnGrid .btn.nextBtn:not(.disabled)')
.click()//Error thrown here
.sleep(2000)
.url()
.should.eventually.become('http://www.somewebsite.com/nextpage');
});
});
由于我在JavaScript方面的有限经验,我尝试了所有我能想到的,但无济于事。 所以无论如何我都可以避免此StaleElementReference错误? 同样,该错误有时仅在执行期间抛出。
您可能想阅读有关Stale Element Reference异常的更多信息。 从您所描述的内容看来,您好像获得了对元素的引用,请在页面上执行一些操作,然后更改/删除引用的元素。 当您对变量引用进行操作时,会出现此错误。 该解决方案实际上取决于您用于执行测试的代码以及用于访问元素的框架。 通常,您需要知道何时执行更改页面和重新获取元素的操作,然后再访问它。 您可以始终在访问元素之前重新获取元素,可以重新获取受页面更改影响的所有元素,依此类推...
您的代码可能看起来像这样
WebElement e = driver.findElement(...); // get the element
// do something that changes the page which, in turn, changes e above
e.click(); // throws the StaleElementReference exception
您可能想要的更像是其中之一...
在需要之前不要获取元素
// do something that changes the page which, in turn, changes e above
WebElement e = driver.findElement(...); // get the element
e.click(); // throws the StaleElementReference exception
...或者在需要之前再次获取它...
WebElement e = driver.findElement(...); // get the element
// do something that changes the page which, in turn, changes e above
e = driver.findElement(...); // get the element
e.click(); // throws the StaleElementReference exception
我更喜欢第一个修复程序……只要需要就可以获取所需的内容。 那应该是解决这个问题的最有效方法。 第二个修复程序可能会出现性能问题,因为您可能会一遍又一遍地重新获取一堆元素,而从不使用它们,或者仅将它们引用一次就重新获取了10次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.