Javascript 异步测试中的额外等待
我有一段代码:Javascript 异步测试中的额外等待,javascript,reactjs,asynchronous,jestjs,enzyme,Javascript,Reactjs,Asynchronous,Jestjs,Enzyme,我有一段代码: async fetchAndUpdate () { const endpoint = 'endpoint' this.setState({ configFetched: false }) try { const response = await window.fetch(`https://${window.location.host}/${endpoint}`, { method: 'POST', credent
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
})
}
当我从第一个代码段中取消注释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)
})
it('返回肯定响应时应设置configFetched',异步(完成)=>{
常量包装器=浅()
fetch.mockClear()
fetch.mockReturnValueOnce(ConstructionSuccessfulResponse(true))
const fetchButton=wrapper.find(fetchButtonSelector)
等待获取按钮。模拟('单击')
设置超时(()=>{
expect(wrapper.state().configFetched).toBeTruthy()
完成()
}, 1)
})
这有多糟糕?每个
wait
都会产生控制,您的测试实际上并不是在等待完整的操作完成。我如何才能做到这一点?摆脱语法上的甜言蜜语,回到承诺是一条出路?对于未来的读者:这本书让我了解了异步如何在JS中工作:谢谢Kyle Simpson!既然您已经在测试函数中使用了async
,我宁愿使用wait Promise.resolve()代码>在执行fetch mock之后才运行。
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)
})