Unit testing with Jest + Vuejs Project
--
As developers we all wants to have bug free codes. The worst nightmare of every developer will be finding out that current changes has breakdown the up and running application. So, as a solution for this, we can follow some good practices to avoid such scenarios. By using a good testing approach will help us to make sure that everything works fine as it is should be.
Basically, testing means that we are checking whether our code is up to meet some expectations. Using a good testing approach will make your code clean, improve quality and low rate of bugs reporting.
In testing there are different types such as unit, integration and e2e testing etc. here we are going to discuss about unit testing. ‘In here individual units or the components of the application is tested.
In this article I’m going to focus on JavaScript library which is used for unit testing. Jest is the library which is going to use for creating and running unit test in our vuejs project.
As special point, it is better if we could start writing test cases from the beginning of the project. At initial stage it may be difficult, because of requirement gathering and not having clear picture of every functionalities at all. But if we going to add test cases to an existing running application it will be somewhat difficult due to some dependency issues that might take place.
As key point, before writing unit test we should have an idea about what areas should be tested. Specially don’t give concern about testing UI related things. Basically the logical functions, algorithms used, services method and other important methods.
In vuejs we can use its official unit testing library Vue Test Util
Vue CLI has built-in support of adding Jest tests while creating with vue-cli.
First I’m going to set up jest for our already created project.
$ vue add unit-jest
This command will update the project folder with necessary files and dependencies for testing purposes. Following files will be changed or added
jest.config.jstests/unit/.eslintrc.jstests/unit/example.spec.jspackage-lock.jsonpackage.json
After the use the below command to add vue test untils as a dev dependency
$ npm install — save-dev @vue/test-utils
Now there will be an example.spec.js file which have been created automatically in under test\unit folder structure. Now if we run the command
npm run test: unit
this example unit test file will be run the test and gives the output result.
For getting some ideas to how to write unit testing for your application:
I have added some example code for unit testing below.
temperature.ts
temperature.spec.ts