反应0.14.5复合组件和儿童的公共方法

时间:2016-01-14 01:14:45

标签: reactjs reactjs-testutils

我正在尝试在React类上测试公共方法。这很容易,你可以在第一个规范中看到,但如果我需要提供上下文,组件需要包装在一个复合组件中,我看不到一种方法来获取子的公共方法(第二个规范)

 it('consider this', function(){
        var Stub = React.createClass({
            doSomething: function() {
                console.log('whoohoo!');
            },
            render: function(){
                return null
            }
        });

        var StubElement = TestUtils.renderIntoDocument(React.createElement(Stub, {}));

        StubElement.doSomething(); //should log
 });

 it.only('now consider this with a context', function(){
     var Stub = React.createClass({
         contextTypes: {
             location: React.PropTypes.object
         },
         doSomething: function() {
             console.log('whoohoo!', this.context.location.pathname);
         },
         render: function(){
             return null
         }
     });

     var ContextWrapper = React.createClass({
         childContextTypes: {
             location: React.PropTypes.object
         },
         getChildContext: function() {
             return {
                 location: window.location
             }
         },
         render: function() {
             return React.createElement(Stub, {})
         }
     });
     var StubElement = TestUtils.renderIntoDocument(React.createElement(ContextWrapper, {}));

     console.log(StubElement);
     // how do I get public access to doSomething() ?

 });

有关如何使用该方法的任何想法?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用findRenderedComponentWithType找到组件本身。

it.only('now consider this with a context', function(){
    var Stub = React.createClass({
        contextTypes: {
            location: React.PropTypes.object
        },
        doSomething: function() {
             console.log('whoohoo!', this.context.location.pathname);
        },
        render: function(){
            return null
        }
    });

    var ContextWrapper = React.createClass({
        childContextTypes: {
            location: React.PropTypes.object
        },
        getChildContext: function() {
            return {
                location: window.location
            }
        },
        render: function() {
            return React.createElement(Stub, {})
        }
     });
     var ContainerComponent = TestUtils.renderIntoDocument(React.createElement(ContextWrapper, {}));
     var StubComponent = TestUtils.findRenderedComponentWithType(ContainerComponent, Stub);

      console.log(Stub.doSomething);

 });