首页 > 解决方案 > 如何获取具有变化值的隐藏元素的文本内容

问题描述

这是我要测试的元素

        <div id="console-modal" class="tab-item hide-item green-outline">
          <p id="message-box"></p>
          <button id="console-modal-button" class="white-button btn-md">close</button>
        </div>

当发生某些操作时,我将向 中添加一条消息<p>并将显示设置<div>为阻止。<p>在我对 selenium 的测试中,我希望得到更新元素中存在的消息。但它返回一个空字符串。

这是执行更新<p>元素操作的代码

  it('should fill the login form and submit', () => {
    driver.findElement(By.id('username')).sendKeys('johnd');
    driver.findElement(By.id('passwd')).sendKeys('12345');
    return driver.findElement(By.id('inline-signin-button')).click();
  });

这是我正在执行的测试,以测试#message-box. 代替innerHTML我也试过了textContent。此外,当我向元素添加一些文本时<p>,测试能够获取内容,但在操作完成并显示框后它没有获取更新的内容。

it('should find the auth error modal and close', () => {
   driver.wait(until.elementLocated(By.id('console-modal')));
   driver.findElement(By.id('message-box')).isDisplayed();
   return expect(driver.findElement(By.id('message-box')).getAttribute('innerHTML')).to.eventually.equal('authentication fail! check your username and password')
driver.findElement(By.id('console-modal-button')).click();
 });

我希望返回的值是<p>元素的更新内容,但它似乎保留了元素仍然隐藏时的内容。有没有办法在显示元素时获取更新的文本内容。或者有没有一种方法可以延迟执行,直到元素在测试之前显示出来。

标签: javascriptseleniumselenium-webdriverhidden

解决方案


您可以使用下面的等待。

var pElement = driver.wait(until.elementLocated(By.xpath("//div[@id='console-modal'][not(contains(@class,'hide-'))]/p[@id='message-box']")));

我们一直等到div类名没有hide,以确保显示块(这将确保 p 文本更新)


推荐阅读