【问题标题】:"ReferenceError: document is not defined" when testing in-browser with mocha webdriver使用 mocha webdriver 在浏览器中测试时出现“ReferenceError:文档未定义”
【发布时间】:2018-08-29 16:49:16
【问题描述】:

我正在使用带有 mocha 的 webdriver。当我尝试使用“document.getElementById”时,我最终得到“ReferenceError: document is not defined”

我正在浏览器内测试(不是无头)。

我发现的任何信息似乎都表明该问题发生在无头测试(即在 Node 中)并且需要 jsdom-global 时。我尝试安装它只是为了看看会发生什么。它摆脱了“ReferenceError:文档未定义”错误,但“document.getElementById”最终会变成未定义(这是有道理的,因为我正在浏览器中进行测试)

我是否更正了在浏览器内测试时我“应该”能够使用“document.getElementById”?

谢谢

注意:这仅适用于一种特殊情况。我知道这不是标准用途。

【问题讨论】:

  • Mocha 对全局变量做了一些奇怪的事情,您可以使用 globals 对象上的 globals 函数来设置它们。

标签: javascript node.js selenium-webdriver mocha.js


【解决方案1】:

如果你想使用浏览器调用而不是 webdriver 的方法,你需要使用executeScript

在您的情况下,考虑到您将收到 id 作为参数:

driver.executeScript(`document.getElementById("${elementId}")`);

【讨论】:

    【解决方案2】:

    如果您尝试使用 selenium 自动化进行浏览器测试,则不应使用 document.getElementById。

    通过 ID 属性定位元素。此定位器使用 CSS 选择器 *[id="$ID"],而不是 document.getElementById。 在这里查看更多 [https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_By.html]

    (更新假设您正在做浏览器测试这是使用 id 的 Mocha 的完整示例:

    var webdriver = require('selenium-webdriver'),
      By = webdriver.By,
      until = webdriver.until;
    
    async function test() {
      var driver = await new webdriver.Builder()
        .usingServer()
        .withCapabilities({ browserName: 'chrome' })
        .build();
    
      await driver.get('http://www.google.com');
    
      let searchField = await driver.findElement(By.id('lst-ib'));
      searchField.sendKeys('webdriver');
    }
    
    describe('Describe test', function() {
      this.timeout(50000);
      it('Some test', function(done) {
        test().then(function() {
          done();
        });
      });
    });
    

    【讨论】:

    • 感谢您的回复。我想我应该提到我知道“document.getElementById”不是硒的标准。我只需要将它用于一种特殊情况。再次感谢
    猜你喜欢
    • 2018-11-13
    • 2021-10-14
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多