[英]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.