How much time have you spent trying to understand what to test in Vue.js? what is testing? How to unit test Vue.js application!
There are a lot of articles and videos out there talking about Vue.js testing with jest, mocha, etc. But many of them assume that people are already familiar with unit testing and know exactly what to test.
- What is Unit Testing in Vue.js? Why do I need it?
- What to Test in Vue.js application?
- Resources to dig deeper
Let's make it simple. Always when you create a new component, you are going to test it manually:
- import that component to your code.
- you open your browser and start asserting that all features are working.
- product name.
- product link on Amazon.
- product image.
HTML card that shows the product name, image and when you click on it, it redirects you to the product's page on Amazon.
- you import this component to your Vue app.
- you open your browser to assert that the HTML card is working, the name and image are rendered correctly and when you click on this card it redirects you to the correct link.
Imagine that your component is working 100% well. one day, you want to add more product details or any kind of feature, you write, update or remove existing code. you go to your browser to check that everything is working but you forgot to click on the card.
After a while, some users tells you that clicking on the product is not working! you are not redirecting any users! you are wasting money!
Actually, you are able to avoid this mistake by unit testing your code, let me show you.
Before we start testing, you have to know:
In Vue.js particularly, don't test logic, don't test methods, functions, watchers ,etc (even filters, don't test it).
Just look at your component from the sky and treat it as a factory that receives inputs to return outputs.
Don't test code that you didn't write!, don't test something other people have already tested it.
Example: don't test
v-model, don't try to assert that clicking on
<a href="google.com"></a> will redirect you to google.com, etc.
Now, let's get back to our subject.
Take a look at ProductViewer component.
Take a look at its code:
What inputs do we have?
- name and link
What output should be tested?
- We must assert that the name of the product exists and equals to our props name.
- We must assert that the image exists and contains the same src of the given slot.
- we must assert that the a tag exists and contains our link in the href attribute (by using css selector like this
- Go to open-source projects and start testing, there are people will review your tests and gives you feedback.
- Download open-source projects and take a look at their tests.
- Read the next section down below.
The software industry moves fast. But if you keep up, you can have an incredible career.