Unit testing is a great way to ensure that the application meets business requirements. They also help you write a new functionality with confidence that you won’t break existing features. In this article, I will walk you through VueJS unit testing configuration. Then, I’ll show you a working example of how you can write tests for your own components.
If you already have a project created with Vue CLI you can skip installation steps and run: vue add @vue/unit-jest
npm install -g @vue/cli
vue create testing-example
Push the enter button to pick the default config.
Then generate a new VueJS project with a basic development setup with unit testing capabilities.cd testing-example
npm install @vue/cli-plugin-unit-jest @vue/test-utils
Append test:unit command to the end of scripts section in package.json:
"scripts": { ... "test:unit": "vue-cli-service test:unit" },
Create jest.config.js file and add the following lines:
module.exports = { preset: '@vue/cli-plugin-unit-jest', collectCoverage: true }
As a result, you’ll be able to run your unit tests and see the code coverage report.
After the configuration step, add simple functionality to HelloWorld.vue component:
<template> <div> <input v-model="name" /> <button @click="formatMsg">Show message</button> <p>{{message}}</p> </div> </template> <script> export default { name: "HelloWorld", data() { return { name: "", message: "" }; }, methods: { formatMsg() { this.message = `Hello ${this.name}`; }, }, }; </script>
In the src folder create __tests__ directory and add file HelloWorld.test.js inside of it.
The following code will test the functionality of the HelloWorld VueJS component:
import { mount } from '@vue/test-utils'; import HelloWorld from '../components/HelloWorld.vue'; describe('HelloWorld test', () => { it('should format message on button click', () => { const wrapper = mount(HelloWorld); const { vm } = wrapper; wrapper.setData({ name: 'Adam', }); const button = wrapper.find('button'); button.trigger('click'); expect(vm.message).toBe('Hello Adam'); }); /* async keyword is needed because of updating the DOM. We need to wait for button click to complete and call formatMsg function. Otherwise the last assertion would fail */ it('should show message on button click', async () => { const wrapper = mount(HelloWorld); const { vm } = wrapper; wrapper.setData({ name: 'Adam', }); const button = wrapper.find('button'); await button.trigger('click'); const p = wrapper.find('p'); expect(p.text()).toBe('Hello Adam'); }); });
‘Describe’ block is used to group unit tests together. In ‘it’ block you can name your test and put your assertions (expect function).
In order to access data of the HelloWorld component, you need to mount it. The vm value unpacked from the wrapper variable will contain properties and methods of the mounted component.
You can call the npm run test:unit
command to check if the tests pass. Additionally, you will get the code coverage report after our tests complete.
Leave a Reply