Reputation: 33
I have a following piece of code:
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}`)
}
}
And I have the test for this:
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
})
}
And it passes with expected output(first code ends, than expect is checked)
End of implementation
Here comes the expect...
Problem starts when I uncomment 4 lines from the first snippet. Test starts to fail, and output is reversed:
Here comes the expect...
End of implementation
Why does this particular piece of code change everything? How can I fix this?
Upvotes: 0
Views: 181
Reputation: 33
I bypassed the problem by putting expect section in setTimeout and by calling done after it's 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)
})
How evil is this?
Upvotes: 1