2015-08-19 39 views
1

我一直在玩reactjsTestUtils。这非常令人沮丧。我不确定,但经过几个小时的试验。在我看来,浅显渲染一个组件后,我不能使用findRenderedComponentWithTypescryRenderedComponentsWithType。实际上,我不知道如何从ReactComponent tree中提取出它的类型。我不知道为什么,因为我对reactjs非常陌生,我不确定我能做什么或不能做什么。浅层渲染组件和scryRenderedComponentsWithType

例如:

var Layout = React.createClass({ 
    render: function(){ 
     console.log(this.props); 
     return (
      <div id="data-trader"> 
       <header className="header"> 
        <LogoElement /> 
        <UserMenu user={this.props.user} /> 
       </header> 
       <div className="container max"> 
        <div className="main"> 
         <RouteHandler path={ this.props.path } query={ this.props.query } params={ this.props.params } user={this.props.user} /> 
        </div> 
        <Footer /> 
       </div> 
      </div> 
     ); 
    } 
}); 

测试:

describe('Shallow Layout', function(){ 
    beforeEach(function(){ 
     fakeDOM = TestUtils.createRenderer(); 
    }); 

    // PASS  
    it('should exist as a component', function(done){ 
     expect(<Layout/>).to.exist; 
     done(); 
    }); 

    // PASS 
    it('should have id=data-trader', function(done){ 
     fakeDOM.render(<Layout />); 
     component = fakeDOM.getRenderOutput(); 

     expect(component.props.id).to.eql('data-trader'); 
     done(); 
    }); 

    it('get children', function(done) { 
     var StubbedComponent = TestHelpers.stubRouterContext(component); 
     var k = TestUtils.findRenderedComponentWithType(StubbedComponent, UserMenu); 
     console.log(k.length); 
     done(); 
    }) 
}); 

我得到这个错误与findRenderedComponentWithType

Error: Did not find exactly one match for componentType:function UserMenu() 

回答

2

我有同样的问题,并通过代码去之后,我发现这个问题是scry/find调用findAllInRenderedTree并测试DOM元素:

https://github.com/facebook/react/blob/master/src/test/ReactTestUtils.js#L48https://github.com/facebook/react/blob/master/src/test/ReactTestUtils.js#L62

鉴于两个测试返回false,该方法返回一个空数组。 (这会导致你在find中描述的错误,并导致scry返回一个空数组)。

我认为这是因为shallowRender的输出不是一个DOM元素(这就是为什么shallowRendere很棒:)。

如果你想找到某种类型的shallowRendered树的第一个孩子,你可以做这样的事情:

findChildrenOfType (view, Component) { 
    if (!view) return null; 

    if (reactTestUtils.isElementOfType(view, Component)) return view; 

    if (view.length) { // is an Array 
     for (let i = 0; i < view.length; i++) { 
     let found = this.findChildrenOfType(view[i], Component); 
     if (found) return found; 
     } 
    } else { 
     if (!view.props || !view.props.children) return null; 
     let children = view.props.children; 

     return this.findChildrenOfType(children, Component); 
    } 
    } 

希望这有助于!