Jest 错误“TypeError:无法读取未定义的属性‘preventDefault’”
2018-12-26
3173
我有一个如下所示的函数,当我要测试该函数时,出现了上述错误。
函数
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
我该如何克服这个错误以及导致上述错误的原因是什么
1个回答
在实例上调用
toggleRecovery
时,您可以传递
preventDefault
模拟,例如
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()
})
Shubham Khatri
2018-12-26