【问题标题】:mocha JSDOM testing on react, getElementById return nullmocha JSDOM 测试反应,getElementById 返回 null
【发布时间】: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;
        }

    }());

【问题讨论】:

    标签: reactjs mocha.js jsdom


    【解决方案1】:

    因此,在 React 中访问已挂载的 DOM 组件的规范方法是使用 ref。不要在 componentDidMount 中使用 document.getElementById() ,而是在渲染元素时使用 ref={(element) =&gt; { /* Do something with element like this.element = element to save it */ }} 。这将获得正确的回调与已安装的 DOM 元素,而无需引用文档。

    应尽可能避免在 React 代码中使用文档,因为它无法进行通用渲染。

    【讨论】:

      猜你喜欢
      • 2019-07-30
      • 1970-01-01
      • 2015-11-23
      • 2023-03-26
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      相关资源
      最近更新 更多