错误:未定义文档

时间:2018-06-26 08:16:12

标签: javascript html angular testing chai

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

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

我将这一行放在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 whoc内部的行是这一行:

NODE_LIST_STRING = Object.prototype.toString.call(document.childNodes),

i删除了此行,并且此错误不再存在。现在,document.getElementById行的错误为document is not defined。 我该怎么办?也许图书馆不推荐使用?

1 个答案:

答案 0 :(得分:0)

document是Node.js环境中未定义的特定于浏览器的全局变量,因此,当您引用document时,柴不知道它是什么以及如何找到它。

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

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

选择一个附带的选项需要更多有关您的用例的知识。