Member-only story
Unit Test Vue Apps with Vue Test Utils — Mock External Dependencies
3 min readJan 14, 2021
With the Vue Test Utils library, we can write and run unit tests for Vue apps easily.
In this article, we’ll look at how to write unit tests with the Vue Test Utils library.
Test Async Behavior Outside of Vue
To test async behavior outside of Vue, we have to mock the async code before we run our test.
For example, if we have a YesNo.vue
component in the components
folder:
<template>
<div>
<button @click="fetchResults">fetch answer</button>
<p>{{ answer }}</p>
</div>
</template><script>
import axios from 'axios'export default {
name: "YesNo",
data() {
return {
answer: undefined
}
},
methods: {
async fetchResults() {
const { data: { answer } } = await axios.get('https://yesno.wtf/api')
this.answer = answer;
}
}
};
</script>
We can test it by mocking the axios
object and put our own get
method in the mocked object:
import { shallowMount } from '@vue/test-utils'
import YesNo from '@/components/YesNo'jest.mock('axios', () => ({
get: () => Promise.resolve({ data: { answer: 'yes' } })
}))