onSubmit = (e) => {
e.preventDefault()
const errors = this.validateForm()
if (!errors) {
const { handleSubmit } = this.props
handleSubmit(e)
}
}
<---------- unit test --------->
it('calls onSubmit prop function when form is submitted', () => {
const onSubmit = jest.fn()
const handleSubmit = jest.fn()
const wrapper1 = mount(<Form handleSubmit={handleSubmit} onSubmit=
{onSubmit} />)
const form = wrapper1.find('form')
form.simulate('submit')
expect(onSubmit).toHaveBeenCalledTimes(1)
})
<----------- HTML ----------->
<Form
onSubmit={this.onSubmit}
render={() => (
<form onSubmit={this.onSubmit} id="submit-form">
<div>
<label>{countryName}</label>
</div>
<input type="submit" id="submit-form" className="invisible" />
</form>
)}
/>
上面的代码段是呈现HTML的示例,而
onSubmit
是用户提交表单时要调用的函数。基本上,此组件是通用表单组件,因此
handleSubmit
是从props中的父组件发送的,并且在我添加了单元测试的情况下,它会生成错误Expected mock function to have been called one time, but it was called zero times.
如果我删除handleSubmit为:
it('calls onSubmit prop function when form is submitted', () => {
const onSubmit = jest.fn()
const wrapper1 = mount(<Form onSubmit=
{onSubmit} />)
const form = wrapper1.find('form')
form.simulate('submit')
expect(onSubmit).toHaveBeenCalledTimes(1)
})
它生成
TypeError: handleSubmit is not a function
错误。 最佳答案
问题在于,在测试中,您正在检查onSubmit
,该组件内部根本没有使用它:
it('calls onSubmit prop function when form is submitted', () => {
const onSubmit = jest.fn() //not used in the component
const handleSubmit = jest.fn()
const wrapper1 = mount(<Form handleSubmit={handleSubmit} onSubmit={onSubmit} />)
const form = wrapper1.find('form')
form.simulate('submit')
expect(onSubmit).toHaveBeenCalledTimes(1) //In component you don't use onSubmit
})
您应该测试
handleSubmit
的用法:it('calls onSubmit prop function when form is submitted', () => {
const handleSubmit = jest.fn()
const wrapper1 = mount(<Form handleSubmit={handleSubmit}/>)
const form = wrapper1.find('form')
form.simulate('submit')
expect(handleSubmit).toHaveBeenCalledTimes(1)
})