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()代码>