Reactjs 如何测试子组件从父组件获取适当的上下文';s getChildContext()?
我有一个组件,它有一个getChildContext()方法,子组件接收从父组件的props派生的上下文 我如何测试他们是否收到了 下面是组件的代码。。。一些选项卡组件Reactjs 如何测试子组件从父组件获取适当的上下文';s getChildContext()?,reactjs,reactjs-testutils,Reactjs,Reactjs Testutils,我有一个组件,它有一个getChildContext()方法,子组件接收从父组件的props派生的上下文 我如何测试他们是否收到了 下面是组件的代码。。。一些选项卡组件 选项卡: 函数_handleTabChange(事件键、id、tabsChange、e){ e、 预防默认值(); tabsChange({id,eventKey}); } const_Tab=({eventKey,children,…props},{activeKey,parentContainer,tabsChange})
选项卡:
函数_handleTabChange(事件键、id、tabsChange、e){
e、 预防默认值();
tabsChange({id,eventKey});
}
const_Tab=({eventKey,children,…props},{activeKey,parentContainer,tabsChange})=>(
);
选项卡容器:
类\u TabContainer扩展组件{
静态显示名称='TabContainer'
静态类型={
子项:PropTypes.node.isRequired,
tabsAddContainer:PropTypes.func.isRequired,
tabsRemoveContainer:PropTypes.func.isRequired,
tabsChange:PropTypes.func.isRequired,
选项卡:PropTypes.object.isRequired,
tabContainerID:PropTypes.string,
}
静态childContextTypes={
parentContainer:PropTypes.string.isRequired,
tabsChange:PropTypes.func.isRequired,
activeKey:PropTypes.number.isRequired,
}
建造师(道具){
超级(道具);
this.clones=Children.map(this.props.Children,(element,eventKey)=>{
如果(元素道具激活){
this.defaultActive=eventKey;
}
console.log(“defaultActive”,this.defaultActive);
返回cloneElement(元素,{eventKey});
});
}
getChildContext(){
const{tabContainerID,tabsChange,tabs}=this.props;
//activeKey是tabs[tabContainerID],除非尚未实例化,在这种情况下
//它是通过映射选项卡以查找具有活动道具的道具而收集的默认活动道具
常量activeKey=(制表符和制表符[tabContainerID]&&tabs[tabContainerID]!=“”)?
选项卡[tabContainerID]:
这是主动的;
返回{
parentContainer:tabContainerID,
activeKey,
塔布桑奇,
};
}
组件willmount(){
const{tabContainerID,tabsAddContainer}=this.props;
if(tabContainerID){
tabsAddContainer({tabContainerID,defaultActive:this.defaultActive});
}
}
组件将卸载(){
const{tabContainerID,tabsRemoveContainer}=this.props;
if(tabContainerID){
tabsRemoveContainer(tabContainerID);
}
}
defaultActive=0;
render(){
const{children,tabsChange,…restProps}=this.props;
返回(
{this.clones}
);
}
}
事实上,这不是必需的-您可以信任getChildContext(),只测试它是否返回预期的数据,而不是通过告诉子对象是否使用了正确的上下文来测试上下文
为此,创建一个函数以返回必要的逻辑并测试该函数,该函数将在getChildContext()中调用