Reputation: 21
I am unit testing my vue-electron project using jest. In a given test i fake a button click to set off a chain of events. Somewhere in that chain i do an axios request to a server, receiving data. However, the test does not await the result and simply goes on and than crashes because the results are not there yet.
First of all i made sure the parameters and the adress of the request where correct, which they were. After that i tried if 'axios' was defined in the component while i was testing is, which was also the case. Than i made sure that if that request was sent, the right response was receiver, which also was the case. And ofcourse i made my test async, hoping that it now would await the results, this was not the case.
Component:
async functionInChain(){
const response = await axios({
url: myUrl,
method: 'POST',
responseType: 'arraybuffer',
params: {
// bind params
},
})
.then((resp: any) => {
// this goes wrong
})
}
test:
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.*/
})
})
I do not get any errors on it, it just wont work
Upvotes: 2
Views: 745
Reputation: 4164
welcome to stackoverflow. I'm not a big expert on jest and the code you've provided is quite minimal but the issue that jumps out to me is your use of await
and promises.
Async and await syntax was introduced as a bit of sugar to make promises nicer. You no longer need to use .then
on your function call if you're using await
. Instead you carry on your code after the await
. So your component code should look more like the following.
Old code:
async functionInChain(){
const response = await axios({
url: myUrl,
method: 'POST',
responseType: 'arraybuffer',
params: {
// bind params
},
})
.then((resp: any) => {
// continue
})
}
New code:
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.
}
If this doesn't solve the issue, it would be worth updating your question with a complete example that we can run ourselves. To do this you should create a minimal piece of code that reproduces the issue and post that (not your whole code solution).
Upvotes: 1