gpt4 book ai didi

javascript - React 中的额外等待会破坏异步测试

转载 作者:行者123 更新时间:2023-12-03 00:35:47 24 4
gpt4 key购买 nike

我有以下代码:

async fetchAndUpdate () {
const endpoint = 'endpoint'
this.setState({ configFetched: false })
try {
const response =
await window.fetch(`https://${window.location.host}/${endpoint}`,
{ method: 'POST',
credentials: 'same-origin'
})

if (!response.ok) {
throw new Error(`statusText: ${response.statusText}, status: ${response.status}`)
}

// const result = await response.json()
// if (!result) {
// throw new Error(`status: ${response.status}, result: false`)
// }

this.setState({ configFetched: true })
console.log('End of implementation')
} catch (exception) {
console.error(`Failed to post data to ${endpoint} endpoint. Error: ${exception}`)
}
}

我对此进行了测试:

it('should set configFetched when positive response is returned', async () => {
const wrapper = shallow(<Component />)
fetch.mockClear()
fetch.mockReturnValueOnce(constructSuccessfulResponse(true))

const fetchButton = wrapper.find(fetchButtonSelector)
await fetchButton.simulate('click')

console.log('Here comes the expect...')
expect(wrapper.state().configFetched).toBeTruthy()
})

const constructSuccessfulResponse = (data) => {
return Promise.resolve({
ok: true,
json: () => data
})
}

它通过了预期的输出(第一个代码结束,比预期被检查)

End of implementation
Here comes the expect...

当我取消第一个代码片段中的 4 行注释时,问题就开始了。测试开始失败,输出反转:

Here comes the expect...    
End of implementation

为什么这段特定的代码会改变一切?我该如何解决这个问题?

最佳答案

我通过将expect部分放在setTimeout中并在完成后调用done来绕过这个问题:

it('should set configFetched when positive response is returned', async (done) => {
const wrapper = shallow(<Component />)
fetch.mockClear()
fetch.mockReturnValueOnce(constructSuccessfulResponse(true))

const fetchButton = wrapper.find(fetchButtonSelector)
await fetchButton.simulate('click')

setTimeout(() => {
expect(wrapper.state().configFetched).toBeTruthy()
done()
}, 1)
})

这有多邪恶?

关于javascript - React 中的额外等待会破坏异步测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53669081/

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