Selenium Web 服务器状态元素引用错误

Selenium Web Server State Element Reference Error

我有几个测试规范,但它阻塞了。其中之一:

  it('Add button should exist', async () => {
    var add = $('[test-id="add"]');
    browser.wait(EC.presenceOf(add), 10372);
    expect(await add.isPresent()).toBeTruthy();
  });

我正在检查此代码块中的 DOM 元素。当我 运行 只有它阻止时,测试成功通过。但是,当我 运行 所有测试规格时,我得到一个错误:

message='Unhandled promise rejection: StaleElementReferenceError: stale element reference: element is not attached to the page document|

我正在使用 protactorselenium web driver。 我也试过相关问题:issue1 issue2

我需要帮助

消息说该元素未附加到 DOM。您应该先等待元素可见,然后再与其交互:

it('Add button should exist', async () => {
browser.wait(EC.presenceOf($('[test-id="add"]'), 10372);
var add = $('[test-id="add"]');  
expect(await add.isPresent()).toBeTruthy();

});

首先你要明白什么是Stale Element Reference Error。 从 Mozilla...

The stale element reference error is a WebDriver error that occurs because the referenced web element is no longer attached to the DOM. ... When an element is no longer attached to the DOM, i.e. it has been removed from the document or the document has changed, it is said to be stale

... 意味着当您第一次与该元素交互时,它被标记为存在,但下次您打算使用该元素时它已经消失但仍被标记为存在,导致错误你现在遇到了。

例如,在您的代码中,

  it('Add button should exist', async () => {
    var add = $('[test-id="add"]');
    browser.wait(EC.presenceOf(add), 10372);
    // Code continues because the element 'add' is present.
    expect(await add.isPresent()).toBeTruthy(); // Stale error is thrown here when the saved element 'add' is not present anymore.
  });

要修复它,只需直接重新查找该元素,而不是从一个实例中引用它。

  it('Add button should exist', async () => {
   browser.wait(EC.presenceOf($('[test-id="add"]')), 10372);
   expect(await $('[test-id="add"]').isPresent()).toBeTruthy();
  });

即便如此,您在这里所做的就像 expect(true).toBeTruthy(); 因为元素存在的预期条件已经通过。