Javascript 笑话错误'';TypeError:无法读取属性';防止违约';“未定义”的定义;

Javascript 笑话错误'';TypeError:无法读取属性';防止违约';“未定义”的定义;,javascript,reactjs,jestjs,Javascript,Reactjs,Jestjs,我有一个如下的函数,当我要测试函数时,我得到了上面的错误 功能 toggleRecovery = e => { e.preventDefault() this.setState( { recovery: !this.state.recovery }, () => { this.props.reset() } ) } 测试 test('if the recovery state

我有一个如下的函数,当我要测试函数时,我得到了上面的错误

功能

toggleRecovery = e => {
    e.preventDefault()
    this.setState(
      {
        recovery: !this.state.recovery
      },
      () => {
        this.props.reset()
      }
    )
  }
测试

test('if the recovery state is true should set the state to the false', () => {
      wrapper.setState({ recovery: true })
      //Check if the state is true initially
      expect(wrapper.state().recovery).toBeTruthy()
      //Calling the toggleRecovery()
      wrapper.instance().toggleRecovery()
      expect(wrapper.state().recovery).toBeFalsy()
      expect(props.reset).toHaveBeenCalled()
    })
错误

TypeError: Cannot read property 'preventDefault' of undefined

在实例上调用
toggleRecovery
时,如何克服此错误以及导致上述错误的原因您可以通过
preventDefault
mock-like

test('if the recovery state is true should set the state to the false', () => {
      wrapper.setState({ recovery: true })
      //Check if the state is true initially
      expect(wrapper.state().recovery).toBeTruthy()
      //Calling the toggleRecovery()
      wrapper.instance().toggleRecovery({ 
          preventDefault: () => {
      })
      expect(wrapper.state().recovery).toBeFalsy()
      expect(props.reset).toHaveBeenCalled()
    })

您没有在此处传递参数
e
。甚至怀疑
e
未定义。另外,
e
需要是事件对象,Jest是否支持事件触发?添加一个
console.log(e)。或
if(e)e.preventDefault()