首页 > 解决方案 > Selenium Web 服务器状态元素引用错误

问题描述

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

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

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

message='未处理的承诺拒绝:StaleElementReferenceError:过时的元素引用:元素未附加到页面文档|

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

我需要帮助。

标签: selenium-webdriverprotractorselenium-rc

解决方案


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

过时的元素引用错误是由于引用的 Web 元素不再附加到 DOM 而发生的 WebDriver 错误。...当一个元素不再附加到 DOM 时,即它已从文档中删除或文档已更改,则称该元素已过时

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

例如,在您的代码中,

  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();因为预期条件已经通过了元素的存在。


推荐阅读