我遵循了 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
什么?
通过您展示的示例,您有一个AlertPanel
组件并对其进行了测试。
SpecialAlertPanel
唯一的功能就是渲染AlertPanel
。
<div>
的测试SpecialAlertPanel
是复制AlertPanel
的测试。
实际上,您需要测试的只是SpecialAlertPanel
是否正在渲染AlertPanel
。如果AlertPanel
通过了测试,SpecialAlertPanel
通过了测试以检查AlertPanel
,那么您已经知道它正在渲染<div>
,而无需显式测试它。
(当然,如果您将来添加额外的功能,则需要添加测试SpecialAlertPanel
)