Test with reactjs renderIntoDocument keep failed due to required DOM

前端 未结 2 1851
梦如初夏
梦如初夏 2021-02-05 16:03

I am new to reactJS and try to learn how to test with it. I have encouter the following testing util method. However i am keep getting the same error message:ReferenceErro

2条回答
  •  时光说笑
    2021-02-05 16:28

    You need a DOM. Fortunately, jsdomify makes it easy to attach a DOM to your globals in Node.

    Suppose we have a simple component:

    var React = require('react');
    module.exports = React.createClass({
      displayName: 'Foo',
    
      componentDidMount: function() {
        console.log('componentDidMount called');
      },
      render: function() {
        return (
          

    hello world

    ); } });

    We can test this with renderIntoDocument. Here's an example using tape:

    var jsdomify = require('jsdomify').default;
    // We don't want to require React until we've set up the DOM
    // (see the jsdomify docs).
    var React;
    
    var test = require('tape');
    
    test('Render a Foo component with full react lifecycle', function (t) {
      jsdomify.create();
      React = require('react');
    
      var Foo = require('../Foo.jsx');
    
      // Full render to trigger componentDidMount.
      var ReactTestUtils = require('react-addons-test-utils');
      var renderer = ReactTestUtils.renderIntoDocument();
      var result = renderer.render();
    
      // Cleans up global variables inserted by jsdomify.create.
      jsdomify.destroy();
    
      t.equal(result.props.children, 'hello world');
      t.end();
    });
    

提交回复
热议问题