2016-01-14 75 views
1

我想在React類上測試公共方法。這很容易,就像你在第一個規範中看到的一樣,但是如果我需要提供上下文,組件需要被包裝在一個複合組件中,並且我看不到一種方法來獲取孩子的公共方法(第二個規範) 。反應0.14.5複合組件和兒童的公共方法

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

}); 

有關如何進入該方法的任何想法?謝謝!

回答

0

您可以使用findRenderedComponentWithType來查找組件本身。

​​
+0

謝謝,@awei,我已經試過了。 Paul O.在Facebook上表示,不能這樣做。 https://github.com/facebook/react/issues/4305,但你可以在上下文中創建一個引用。 – 4m1r