At some point, any serious development project should implement testing for their components. Generally, the first step is unit testing. Unit testing allows you to ensure that the behavior of your individual components is reliable and consistent. By using Karma and Mocha, combined with Webpack, we can unit-test Vue components with relative ease.
There’s no soft way to put it, the JavaScript web app testing scene is a complicated beast. As a result, the configuration required for a successful unit-testing setup is fairly extensive. Accordingly, you’ll probably be best off using vue-cli with the webpack template ($ vue init webpack my-project) and testing enabled.
Even then, there are some configuration changes to make to test/unit/karma.conf.js. You’ll need to specify the plugins you’re using, and possibly change the launcher. In this case, I’m using karma-chrome-launcher instead of karma-phantomjs-launcher.
Let’s create a small component to test.
Now we’ll add a spec for it in test/unit/specs. This just checks that the component’s text is set to the property value.
Vue updates the DOM asynchronously, in ticks. Therefore, when we modify anything that affects the DOM, we need to wait for the DOM to update using Vue.nextTick() before making any assertions.
Hopefully that helps get you started!
However, the way components are instanced and extended in Vue can be a bit confusing, so you may want to take a look at the official Vue tests to get a better idea on how to test various component capabilities.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!