我正在使用玩笑对我的电子电子项目进行单元测试。在给定的测试中,我伪造了一个按钮单击以引发一系列事件。我在那个链的某个地方向服务器发出axios请求,接收数据。但是,测试不会等待结果,只是继续进行,然后崩溃,因为结果还不存在。
首先,我确定请求的参数和地址正确无误。之后,我尝试在测试期间是否在组件中定义了“ axios”,情况也是如此。比起我确定如果发送了该请求,正确的响应就是接收者,情况也是如此。当然,我使我的测试异步,希望它现在可以等待结果,事实并非如此。
组件:
async functionInChain(){
const response = await axios({
url: myUrl,
method: 'POST',
responseType: 'arraybuffer',
params: {
// bind params
},
})
.then((resp: any) => {
// this goes wrong
})
}
测试:
describe('component.vue', async() => {
test('call runBot() and see if it reacts', async() => {
wrapper.find('v-btn.button-i-use').trigger('click')
/*later on i expect a value to be true, however it never is.
By setting different "checkpoints" i found out things go wrong in the axios request.*/
})
})
我没有收到任何错误,只是无法正常工作
答案 0 :(得分:1)
欢迎使用stackoverflow。我不是玩笑的专家,您提供的代码很少,但是让我跳出来的问题是您使用await
和promises。
引入了异步和等待语法,以使承诺更好。如果您使用的是.then
,则不再需要在函数调用上使用await
。相反,您在await
之后继续执行代码。因此,您的组件代码应更像以下内容。
旧代码:
async functionInChain(){
const response = await axios({
url: myUrl,
method: 'POST',
responseType: 'arraybuffer',
params: {
// bind params
},
})
.then((resp: any) => {
// continue
})
}
新代码:
async functionInChain(){
const response = await axios({
url: myUrl,
method: 'POST',
responseType: 'arraybuffer',
params: {
// bind params
},
})
// continue, as if you were now in the ".then" function, because you "await"ed.
}
如果这不能解决问题,则值得以我们可以自行运行的完整示例更新您的问题。为此,您应该创建最少的代码来重现问题并将其发布(而不是整个代码解决方案)。