gpt4 book ai didi

reactjs - 如何为调用 props 中接收的函数的函数添加单元测试

转载 作者:行者123 更新时间:2023-12-03 14:24:30 25 4
gpt4 key购买 nike

 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 was called one time ,但它被调用了零次。如果我将 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不是函数错误。

最佳答案

问题是在测试中您正在检查 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)
})

关于reactjs - 如何为调用 props 中接收的函数的函数添加单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57768849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com