Implement Unit Testing into Vue Application

Unit testing is a way to ensure your code already running as expected. It is a fit solution to avoid a somethings bad or wrong on the development product. (Rohmad, 2018)
Unit testing involves breaking your program into pieces, and subjecting each piece to a series of tests. (MattJ, 2016)
Implement of Unit testing, probably will bit spend your time. But to avoid does somethings wrong in the future, it’s a great way to make finished development and done as expected.
Vue application consist of some components that probably reusable and has task specifically.
Here I will share with you all, about tips for implement unit testing into your Vue Application.
I assume, that you are already understand about Vue.js & Vuex at least basic knowledge.
For get started, we would build an application that added unit testing into each its component, also into Vuex store.
Setup Project
You have to clone this repository first. However if you want to implement into your existing application. You can skip this step.
git clone https://github.com/rohmad-st/vue-learning-app.gitUnit Testing in Component
From above project, now we have a component Product.vue. I’m using Vuetify as base design system. So if you unfamiliar with it, you have to read it first in https://vuetifyjs.com/en/getting-started/quick-start:
I hope you already familiar with Vuex, because here we will also learn how to implement unit testing into Vuex.
Look at Product.vue component above, now we will try to write an unit testing for it. Here we are have challenges, for also make sure Vuetify and Vuex can run as well, so some steps that I do:
- import Vuetify and Vuex into our file testing.
- give a mock testing into actions and getters of vuex
In this component I have expected that a class headline will have title equal with title of product props [code line: 28–36]
- line 29: prepare a data model product
- line 33: put our mock data of product into props param
Unit Testing into Vuex Stores
We have a module products.js to handle all events in the product actions.
From vuex module above, now we will added line codes to test it.
Our expected are:
- make sure response of getAll() is correct, the output has result that same with data mockup. (code line: 17–23)
- make sure action toggle favorite work as well. can doing both of add and remove as favorite. (code line: 25–40)
- Check favoriteIndex getter get correct index. (code line: 42–48)
- Check isFavorite getter get correct result. (code line: 50–52)
Now you already can implemented an unit testing into both of vue component and vuex.
Feel free to discuss and share it if you feel this article is helpful. :)
