[英]Jest not recognizing spy is called
我在使用Jest調用我的函數時遇到了一些麻煩。 我有兩個模擬函數。 一個只是為了返回承諾而被嘲笑,另一個是應該在第一個的then()
塊中調用的簡單間諜。
下面,在測試中,您將看到兩個期望。 第一個期望通過了。 第二個沒有。 即expect(sendSpy).toHaveBeenCalled()
通過,但是expect(sendCallbackSpy).toHaveBeenCalled()
沒有通過。
但是,當我將console.log
語句放入文件中(如下所示)時,兩者都執行(即“ before”和“ after”),並且如果我在控制台中記錄window.props.onSend
則它確認模擬的函數是當下。 因此,看起來該函數應該被調用。
值得注意的另一件事是,我的實現要求我從window
中的props
對象中傳遞回調。 此外,要在Jest中模擬window
中的內容,請按照下面的操作模擬global
。 我認為這與問題無關,但仍然值得指出。
可能是在then()
塊中調用實際函數之前運行了期望嗎?
export class MyButton extends Component {
handleClick = () => {
this.props.send(this.props.url).then(res => {
console.log('before', window.props.onSend)
window.props.onSend(res.data)
console.log('after')
})
}
render() {
return <button onClick={handleClick} />
}
}
//test
test('it calls the identity function when button is clicked', () => {
const sendSpy = jest.fn(() => { return Promise.resolve({ data: 'hello' }) })
const sendCallbackSpy = jest.fn()
global.props = { onSend: sendCallbackSpy }
wrapper = shallow(<MyButton send={sendSpy} } />)
const button = wrapper.find('button')
button.simulate('click')
expect(sendSpy).toHaveBeenCalled()
expect(sendCallbackSpy).toHaveBeenCalled()
})
您需要等待諾言才能測試第二個間諜:
test('it calls the identity function when button is clicked', async() => {
const request = Promise.resolve({ data: 'hello' })
const sendSpy = jest.fn(() => request)
const sendCallbackSpy = jest.fn()
global.props = { onSend: sendCallbackSpy }
wrapper = shallow(<MyButton send={sendSpy} } />)
const button = wrapper.find('button')
button.simulate('click')
expect(sendSpy).toHaveBeenCalled()
await request
expect(sendCallbackSpy).toHaveBeenCalled()
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.