Reactjs 为单击时调用的函数编写测试

Reactjs 为单击时调用的函数编写测试,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,我一直在尝试为我构建的react组件编写一些测试。组件在单击某个按钮(这是另一个组件)时将值传递给其容器 从“道具类型”导入道具类型; 从“../../common/components/Button”导入按钮; 从“../../common/components/Input”导入输入; 从“类名称”导入类名称; 类AddNewCellInputs扩展了React.Component{ 状态={value:'',shortName:''} onChange=(e)=>{ 设值=e.target.

我一直在尝试为我构建的react组件编写一些测试。组件在单击某个按钮(这是另一个组件)时将值传递给其容器

从“道具类型”导入道具类型;
从“../../common/components/Button”导入按钮;
从“../../common/components/Input”导入输入;
从“类名称”导入类名称;
类AddNewCellInputs扩展了React.Component{
状态={value:'',shortName:''}
onChange=(e)=>{
设值=e.target.value;
this.setState({value:value})
}
onShortNameChange=(e)=>{
让shortName=e.target.value;
this.setState({shortName:shortName})
}
onAddCellSubmit=()=>{
const{value,shortName}=this.state
this.props.onAddCellSubmit(缩写名,值)
this.setState({value:'',shortName:''})
}
render(){
const{active,onNewCellClick}=this.props;
const{value,shortName}=this.state
返回(
输入单元格名称
this.onChange(e)}/>
这个.onShortNameChange(e)}/>
this.onAddCellSubmit(shortName,value)}text=“添加单元格”/>
);
}
}
导出默认AddNewCellInputs;
};
这是测试

it('renders Call the addCellubmitMethod on lick of hte add-cell button', () => {
  const props = {
    active: true,
    onAddCellSubmit
  };
  let wrapper = mount(<AddNewCellInputs {...props} />);
  const onAddCellSubmit = jest.fn();
  wrapper.find('button').first().simulate('click');
  expect(onAddCellSubmit).toHaveBeenCalled();

});
it('renders在单击添加单元格按钮时调用addCellubmitMethod',()=>{
常量道具={
主动:对,
onAddCellSubmit
};
让wrapper=mount();
const-onaddcellsmit=jest.fn();
wrapper.find('button').first().simulate('click');
期望(onAddCellSubmit).tohavebeincalled();
});
这就是我得到的错误

未捕获[TypeError:\u this.props.onAddCellSubmit不是函数]


我是测试新手,所以如果我做了一些完全错误的事情,请原谅我。

您可以这样尝试

it('renders Call the addCellubmitMethod on lick of hte add-cell button', () => {
  const props = {
    active: true,
    onAddCellSubmit
  };
  let wrapper = mount(<AddNewCellInputs {...props} />);
  const onAddCellSubmitSpy = jest.spyOn(wrapper.instance(),'onAddCellSubmit');
  wrapper.find('button').first().prop('handleClick')();
  expect(onAddCellSubmitSpy).toHaveBeenCalled();
});
it('renders在单击添加单元格按钮时调用addCellubmitMethod',()=>{
常量道具={
主动:对,
onAddCellSubmit
};
让wrapper=mount();
const-onAddCellSubmitSpy=jest.spyOn(wrapper.instance(),'onAddCellSubmit');
find('button').first().prop('handleClick')();
期望(onAddCellSubmitSpy).toHaveBeenCalled();
});

使用后,您正在定义onAddCellSubmit。由于存在临时死区,这甚至不应该起作用。在安装组件后,您似乎正在创建
jest.fn()
,在此之前,onAddCellSubmit是什么?再次检查您是否通过了测试中道具中的
onAddCellSubmit
函数。如果是,请提供完整的测试文件这是我目前为止唯一的测试。。。aoart避免在组件不崩溃的情况下渲染组件
it('renders Call the addCellubmitMethod on lick of hte add-cell button', () => {
  const props = {
    active: true,
    onAddCellSubmit
  };
  let wrapper = mount(<AddNewCellInputs {...props} />);
  const onAddCellSubmitSpy = jest.spyOn(wrapper.instance(),'onAddCellSubmit');
  wrapper.find('button').first().prop('handleClick')();
  expect(onAddCellSubmitSpy).toHaveBeenCalled();
});