如何解决测试一个函数,并没有为.toHaveBeenCalled方法获得正确的结果
我正在测试以下功能:
onSubmit = e => {
e.preventDefault()
if (!this.state.measureURI) return
this.setState({ foodId: this.props.food.foodId },() => this.props.fetchServing({
quantity: parseInt(this.state.quantity),measureURI: this.state.measureURI,foodId: this.state.foodId
}))
}
测试:
test('should test onSubmit prop for valid form submission',() => {
const onSubmit = jest.fn()
const fetchServing = jest.fn()
const arg = {
quantity: expect.any(Number),measureURI: expect.any(String),foodId: expect.any(Number)
}
const wrapper = shallow(<ServingForm food={food} onSubmit={onSubmit} fetchServing={fetchServing} />)
wrapper.find('form').simulate('submit',{
preventDefault: () => { }
})
expect(fetchServing).toHaveBeenCalled()
})
但是,出现以下错误:
● <ServingForm /> › should test onSubmit prop for valid form submission
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
37 | preventDefault: () => { }
38 | })
> 39 | expect(fetchServing).toHaveBeenCalled()
| ^
40 | })
41 |
42 | })
我在做什么错了?
我正在用玩笑和酵素对间谍进行单元测试。
解决方法
您的测试代码永远不会到达fetchServing
调用,因为this.state.measureURI
没有值,因此它只是在那一点返回。我对酶不熟悉,但是根据docs,wrapper
具有setState
功能,因此您可以:
wrapper.setState({ measureURI: 'whatever' });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。