[英]Testing a composed Reactjs component with Enzyme
我遵循了React文档的建议,通过合成来创建一个专门的组件:
export default class AlertPanel extends React.Component {
constructor(props) {
super(props);
}
render() {
textRows = <div>{this.props.text}</div>;
}
return (
<Alert bsStyle={this.props.style} onDismiss={this.props.onDismiss}>
{textRows}
</Alert>
);
}
...和...
import React from 'react';
import AlertPanel from './AlertPanel';
export default class SpecialAlertPanel extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<AlertPanel text="special" />
) ;
}
}
AlertPanel
有通过测试:
it( 'should render AlertPanel to a div', function() {
const wrapper = shallow( <AlertPanel /> );
expect( wrapper.type() ).to.eql( 'div' );
});
我认为等效的测试将对SpecialAlertPanel
:
it( 'should render SpecialAlertPanel to a div', function() {
const wrapper = shallow( <SpecialAlertPanel /> );
expect( wrapper.type() ).to.eql( 'div' );
});
但是此测试失败:
expected [Function: AlertPanel] to deeply equal 'div'
我的测试或代码有错误吗?
由于您进行了浅层渲染,因此SpecialAlertPanel会向下渲染到AlertPanel,而不是“更深”( http://airbnb.io/enzyme/docs/api/ShallowWrapper/shallow.html )
最有可能你需要类似的东西
it( 'should render SpecialAlertPanel to a div', function() {
const wrapper = shallow( <SpecialAlertPanel /> );
expect(wrapper.find(AlertPanel).shallow().type()).to.eql('div');
});
来自https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/type.md :
如果是复合组件,则它将是组件构造函数。
因此, SpecialAlertPanel
的包装器类型为AlertPanel
。
如果您希望测试通过, AlertPanel
包裹在div
。
与@Igor和@RemLampa的正确答案略有不同。 关于它的另一种观点是-您应该为SpecialAlertPanel
测试SpecialAlertPanel
?
在显示的示例中,您具有AlertPanel
组件并且已经过测试。
SpecialAlertPanel
的唯一功能是呈现AlertPanel
。
为<div>
测试SpecialAlertPanel
将复制AlertPanel
的测试。
实际上,您需要测试的只是SpecialAlertPanel
是否正在呈现AlertPanel
。 如果AlertPanel
通过了测试,而SpecialAlertPanel
通过了测试以检查AlertPanel
,那么您已经知道它正在呈现<div>
,而无需显式测试。
(当然,如果将来要添加其他功能,则需要向SpecialAlertPanel
添加测试)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.