小编典典

由于需要DOM,使用reactjs renderIntoDocument进行测试保持失败

reactjs

我是ReactJS的新手,并尝试学习如何对其进行测试。我已经封装了以下测试util方法。但是我一直在遇到同样的错误message:ReferenceError: document is not defined


renderIntoDocument

ReactComponent renderIntoDocument(
  ReactElement instance
)

将组件渲染到文档中的分离DOM节点中。此功能需要DOM。

注意:导入React之前,您将需要在全局范围内使用window,window.document和window.document.createElement。否则React会认为它无法访问DOM,而setState之类的方法将无法工作。


我知道这是缺少DOM的原因,但是如何插入DOM或要求它呢?


我的测试如下:

import expect from 'expect.js';
import React from 'react';
import Header from '../../components/header';
import {renderShallow} from './help';
import ReactAddOn from 'react/addons';

var TestUtils = ReactAddOn.addons.TestUtils;

describe('Test react', function() {
  let component;

  beforeEach(()=>{
    component = TestUtils.renderIntoDocument(<Header></Header>);
  });


  it('Test if the content been correclty render', function() {
    console.log(component);
  });
});

阅读 369

收藏
2020-07-22

共1个答案

小编典典

tl; dr; 您需要jsdom+ Mocha


根据规范ReactTestUtils#renderIntoDocument

renderIntoDocument()需要一个DOM

在导入React之前,您将需要在全局范围内使用window,window.document和window.document.createElement。否则React会认为它无法访问DOM,而setState之类的方法将无法工作。

传统上,React中的单元测试使用来完成Jest,其中显然包含DOM支持。而且Mocha没有。

要理解这一点,请考虑将其简化为类比Jest= Mocha+ jsdom

jsdom是用JavaScript实现的,我们无需浏览器即可使用类似DOM的API。这就意味着我们不必进行顺序测试就可以捕获浏览器,例如Karma(这就是为什么在您使用时就起作用Karma)。因此,我们可以在没有浏览器的环境中运行测试,例如在Node或持续集成环境中。


参考文献:

  1. 教程:在Jsdom上测试React
  2. React规范:ReactTestUtils#renderIntoDocument
  3. 信息:如何开玩笑
  4. 信息:react-testing-mocha-jsdom
2020-07-22