Unit testing 如何对组件进行单元测试?

Unit testing 如何对组件进行单元测试?,unit-testing,reactjs,chai,enzyme,Unit Testing,Reactjs,Chai,Enzyme,我正在尝试对我的reactjs组件进行单元测试: 从“React”导入React; 从“反应模态”导入模态; 从“../../../store”导入存储 从“lodash”导入lodash 导出类AddToOrder扩展React.Component{ 建造师(道具){ 超级(道具); this.state={checked:false} //调试器 } checkBoxChecked(){ 返回真值 } render(){ log('testing=this.props.id',this.p

我正在尝试对我的reactjs组件进行单元测试:

从“React”导入React;
从“反应模态”导入模态;
从“../../../store”导入存储
从“lodash”导入lodash
导出类AddToOrder扩展React.Component{
建造师(道具){
超级(道具);
this.state={checked:false}
//调试器
}
checkBoxChecked(){
返回真值
}
render(){
log('testing=this.props.id',this.props.id)
返回(
增加订单
)
}
}

导出默认AddToOrder你就快到了。只需将您的期望更改为:

expect(wrapper.instance().checkBoxChecked()).equals(true);

您可以详细了解使用酶测试组件方法的更多信息。

对于那些发现公认答案无效的人,在使用
.instance()
之前,请尝试在浅包装上使用
.dive()

参考资料:

扩展先前的答案。 如果已连接组件(Redux),请尝试下一个代码:

 const store=configureStore();
  const context = { store };
   const wrapper = shallow(
      <MyComponent,
      { context },
    );
   const inst = wrapper.dive().instance();
   inst.myCustomMethod('hello');
const store=configureStore();
const context={store};
常数包装=浅(

为什么要导出组件两次?为了避免错误,可以通过导入{shallow,mount}导入一次从“酶”开始;不是两个进口,一个用于mount,一个用于shallowHello,真的很感谢你的解决方案,它也帮了我很多。你知道有没有一种方法可以在没有酶的情况下用纯粹的玩笑来测试组件函数?嘿@AttilaMolnár回复得很晚,但你应该能够做到
MyComponent.prototype.method()
.React只需将方法附加到
原型上即可。这太棒了!感谢这样的回答,我能够比以往更多地了解测试:)谢谢@实际上不起作用的xenetics,因为closure只有当您将组件包装在某种东西中时才需要它,例如Redux connect方法。
 const store=configureStore();
  const context = { store };
   const wrapper = shallow(
      <MyComponent,
      { context },
    );
   const inst = wrapper.dive().instance();
   inst.myCustomMethod('hello');