1

React クラスでパブリック メソッドをテストしようとしています。最初の仕様でわかるように、これは簡単ですが、コンテキストを提供する必要がある場合は、コンポーネントを複合コンポーネントでラップする必要があり、子のパブリック メソッド (2 番目の仕様) にアクセスする方法がわかりません。 .

 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() ?

 });

その方法に到達する方法についてのアイデアはありますか? ありがとう!

4

1 に答える 1

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);

 });
于 2016-01-14T01:23:17.620 に答える