“Stale element reference” error behavior undestanding

前端 未结 2 1164
萌比男神i
萌比男神i 2021-02-09 04:52

Code 1:

element(by.id(\'myButtonId\')).click();
return element(by.id(\'myValidationSummaryId\')).getText().then(function (val) {
    return val;         


        
2条回答
  •  隐瞒了意图╮
    2021-02-09 05:31

    I don't think we can be certainly sure why that happens, but you're definitely not alone (1) (2). This may be due to the way your page is rendered specifically (e.g. how your app/framework is handling rendering DOM elements), or just a Selenium/driver thing. If you're interested into an exact explanation, you might have better luck if using Protractor bug report system.

    A good guess, however, may be that it is related to the way Selenium defines stale element:

    A less common, but still common cause is where a JS library has deleted an element and replaced it with one with the same ID or attributes

    Some libraries can fool Selenium into believing an element is gone from the DOM, but it has been really just replaced in an instant. Adding there a tight, frail timing between clicking and element being placed in the DOM (race condition basically) - that might be the cause. You might be interested in reading a little more about it here.

    Anyway, if you're having such issues, I'd recommend you using browser.wait and Expected Conditions.

    Expected conditions are basically functions that return true or false, and you can specify a timeout that will cause test to fail if true is not returned in that time - you can see how it's used in a similar question.

    Basically, you might want to do it like this:

    var EC = protractor.ExpectedConditions;
    var summaryId = element(by.id('myValidationSummaryId'));
    
    browser.wait(EC.presenceOf(summaryId), 5000);
    //rest of your code
    

提交回复
热议问题