簡體   English   中英

測試 function 並沒有得到 .toHaveBeenCalled() 方法的正確結果

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM