[英]How to expect().toHaveBeenCalled on a function from a mocked function
[英]Testing a function and not getting correct result for .toHaveBeenCalled() method
我正在測試以下 function:
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 | })
我究竟做錯了什么?
我正在使用 jest 和 enzyme 對間諜進行單元測試。
您的測試代碼永遠不會到達fetchServing
調用,因為this.state.measureURI
沒有值,因此它只會在此時返回。 我不熟悉酶,但根據文檔, wrapper
具有setState
功能,因此您可以:
wrapper.setState({ measureURI: 'whatever' });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.