【发布时间】:2016-09-03 13:32:01
【问题描述】:
我正在使用 mocha 和 JsDom 来测试我的 react 组件。
首先我的组件运行良好,所以这是测试环境的问题。
情况:
我有一个组件可以渲染几个带有 id 的 select 标签。然后组件中的componentDidMount 将使用document.getElementById 获取这些选择标签并向它们添加选项。但是当我运行测试时,这些 getElementById 显示为 null。
现在,如果我注释掉 componentDidMount,并断言如下内容,它可以完美运行,因此组件确实渲染了这些选择标签。
describe('test component', function(){
var renderedElement = ReactTestUtils.renderIntoDocument(<Component/>);
var renderedNode = ReactDom.findDOMNode(renderedElement);
it('should have the proper markup', function(){
assert.equal(renderedNode.childElementCount, 5);
[...]
})
})
是什么导致了问题?是不是因为document.getElementById 我的测试环境中不存在文档对象导致我使用的是“假”对象,如果是,我应该如何测试?
下面是我为 mocha 设置的 jsdom
(function () {
'use strict';
var jsdom = require('jsdom'),
baseHTML,
window;
if (!global.window) {
baseHTML = '<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8"><title>Tests</title></head><body></body></html>';
window = jsdom.jsdom(baseHTML).defaultView;
global.window = window;
global.document = window.document;
global.navigator = window.navigator;
}
}());
【问题讨论】: