我有以下一段代码:
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
为什么这段特定的代码会改变一切?我该如何解决?
答案 0 :(得分:0)
我通过将期望部分放在setTimeout中并在完成后调用完成来绕过该问题:
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)
})
这有多邪恶?