Reactjs 在另一个函数中测试一个函数

Reactjs 在另一个函数中测试一个函数,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,您好,我试图在另一个函数中测试一个函数,该函数需要第二个函数外部的参数 export const DetailsView=({intl,object,onClose})=>{ //一些代码 const getIsLogbookAllowed=()=>{ 返回对象&&object.driver; }; //更多代码 }; 尝试测试这个函数onLogbookReportModalClose,但我认为当我执行实例时,变量对象并没有读取它,它被转换为null 测试 test('should retur

您好,我试图在另一个函数中测试一个函数,该函数需要第二个函数外部的参数

export const DetailsView=({intl,object,onClose})=>{
//一些代码
const getIsLogbookAllowed=()=>{
返回对象&&object.driver;
};
//更多代码
};
尝试测试这个函数
onLogbookReportModalClose
,但我认为当我执行实例时,变量对象并没有读取它,它被转换为null

测试

test('should return \'false\' when there is no driver', () => {
    const wrapper = shallow(<DetailsView {...props} />)
    const instance = wrapper.instance()
    expect(instance.getIsLogbookAllowed()).toBe(true)
}
test('在没有驱动程序时应返回'false',()=>{
常量包装器=浅()
const instance=wrapper.instance()
expect(instance.getIsLogbookAllowed()).toBe(true)
}
错误:

TypeError:instance.getIsLogbookAllowed不是函数


有什么建议吗?

这是因为
getIsLogBookAllowed
不是组件实例的属性,它是未定义的,因此不是函数

你应该这样做:

export class DetailsView extends Component {
  getIsLogBookAllowed = () => this.props.object && this.props.object.driver;

  render() {
    return <JSX />
  }
}
导出类详细信息视图扩展组件{
getIsLogBookAllowed=()=>this.props.object&&this.props.object.driver;
render(){
返回
}
}

通过这种方式,函数成为组件实例的一部分,您可以用函数替换类,这也会起作用。

这是因为
getIsLogBookAllowed
不是组件实例的属性,它是未定义的,因此不是函数

你应该这样做:

export class DetailsView extends Component {
  getIsLogBookAllowed = () => this.props.object && this.props.object.driver;

  render() {
    return <JSX />
  }
}
导出类详细信息视图扩展组件{
getIsLogBookAllowed=()=>this.props.object&&this.props.object.driver;
render(){
返回
}
}

通过这种方式,函数成为组件实例的一部分,您可以用函数替换类,这也行。

允许GetIsLogBook在哪里?函数在哪里使用?您是否可以根据函数的结果测试组件是否正确呈现/向子组件传递正确的道具,而不是直接测试正在使用函数本身?@etarhan yes(使用另一种方法)?允许使用GetIsLogBook的位置?函数使用的位置?您是否可以测试组件是否根据函数结果正确渲染/将正确的道具传递给子组件,而不是直接测试函数本身?@etarhan yes(使用另一种方法)