【问题标题】:Error: document is not defined错误:文档未定义
【发布时间】:2018-06-26 08:16:12
【问题描述】:

我想使用 Chai 测试 HTML eemnet 的属性,如下所示:

const chai = require('chai');
const expect  = chai.expect;
expect(document.getElementById('ref_button')).to.have.attr('disabled');

我把这行放在 fr chai-dom chai.use(require('chai-dom')) 它引发了错误:

Unhandled rejection ReferenceError: document is not defined at     
C:\Users\67563478\new_workspace\onconsup\node_modules\chai-dom\chai-dom.js:69:53 at Object.exports.use
(C:\Users\67563478\new_workspace\onconsup\node_modules\chai\lib\chai.js:39:5)
而在 chai-dom 中出现错误的行是这样的:
NODE_LIST_STRING = Object.prototype.toString.call(document.childNodes),

我删除了这条线,并且该错误不再存在。现在,document.getElementById 行的错误是document is not defined。 我该怎么办?也许图书馆 chai-dom 已被弃用?

【问题讨论】:

    标签: javascript html angular testing chai


    【解决方案1】:

    document 是浏览器特定的全局变量,它没有在 Node.js 环境中定义,所以当您引用 document 时,chai 不知道它是什么以及如何找到它。

    此外,(可能 - 因为您没有展示 HTML 文件是如何连接到 chai 的)按钮和它的测试之间没有连接。

    要解决问题,您可以查看实现 WHATWG DOM 和 HTML 标准的 JSDOM (https://github.com/jsdom/jsdom)。或者,您可以选择使用无头浏览器,例如无头 chrome (https://github.com/GoogleChrome/puppeteer)。

    选择要使用的选项需要对您的用例有更多了解。

    【讨论】:

    • 我不能用其他东西来引用 HTMl 元素而不是文档吗?
    • 关于按钮和测试之间的连接,我可以做什么样的连接?我在前面的步骤中使用量角器 element(by.css("*[id='button']")).sendKeys 或示例,它可以在不进行任何连接的情况下工作
    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 2022-10-17
    • 2023-02-02
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多