浅渲染组件和scryRenderedComponentsWithType
Shallow render component and scryRenderedComponentsWithType
本文关键字:scryRenderedComponentsWithType 组件 更新时间:2023-09-26
我一直在玩reactjs
TestUtils
。这很令人沮丧。我不确定,但经过几个小时的实验。在我看来,浅渲染组件后,我不能使用findRenderedComponentWithType
或scryRenderedComponentsWithType
。事实上,我不确定如何从ReactComponent tree
中按其类型提取对象。我不知道为什么,因为我对reactjs
很陌生,我不确定我能做什么或不能做什么。
的例子:
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()
我有同样的问题,通过代码后,我发现问题是scry/find调用findAllInRenderedTree和测试一个DOM元素:
https://github.com/facebook/react/blob/master/src/test/ReactTestUtils.js#L48和https://github.com/facebook/react/blob/master/src/test/ReactTestUtils.js#L62
如果两个测试都返回false,则该方法返回一个空数组。(这会导致你在find中描述的错误,并导致scry返回一个空数组)。
我认为这是因为输出的shallowRender不是一个DOM元素(这就是为什么shallowRender是伟大的:)。
如果你想找到某个类型的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);
}
}
希望这对你有帮助!
相关文章:
- 没有找到相关文章