我的父组件根据状态{ conditionMet : true }呈现一个<Child1 />组件。
如何编写一个测试来检查子组件本身的呈现,而不是组件内字符串的呈现?我想避免使用setTimeout()。
这是我如何构建测试的问题吗?或者,我是如何构建组件的?在Jest / Enzyme中是否存在一个已知的限制或bug,阻止检查子组件是否已呈现?
React: 16.6.3 Jest: 23.6.0酶: 3.7.0酶-接头-react-16
ParentComponent的Jest单元测试
describe('ParentComponent', () => {
test('renders Child1 component when conditionMet is true', () => {
const parentMount = mount(<ParentComponent />);
const param1 = "expected value";
const param2 = true;
parentMount.instance().checkCondition(param1, param2); // results in Parent's state 'conditionMet' === 'true'
//This is not working - the length of the Child1 component is always 0
expect(parentMount.find(Child1)).toHaveLength(1);
//This alternate option passes, but it's not testing the rendering of the component!
expect(parentMount.text()).toMatch('Expected string renders from Child1');
});
});ParentComponent.js
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
conditionMet: false
};
}
checkCondition = (param1, param2) => {
if (param1 === 'expected value' && param2 === true)
{
this.setState({conditionMet: true});
} else {
this.setState({conditionMet: false});
}
this.displayChildComponent();
}
};
displayChildComponent() {
if (this.state.conditionMet) {
return(
<Child1 />
)
}
else {
return(
<Child2 />
)
}
}
render() {
return (
<div className="parent-container">
{this.displayChildComponent()}
</div>
);
}
}发布于 2018-12-27 18:33:23
我想,这可能是一个漫长的解决方案。但它是有效的。
向孩子发送一个道具,这是一个函数,当孩子挂载时调用该函数。
挂载为,
<Clild1 sendConfirmation={this.receiveConfirmation.bind(this)} />在parent中:
receiveConfirmation(e, rendered_child){ this.setState({rendered_child}) }在Child1中:
componentDidMount(){this.props.sendConfirmation(1);}现在,如果您可以检查Parent的状态,则可以始终检查this.state.rended_child的值。
https://stackoverflow.com/questions/53941580
复制相似问题