This tutorial aims to guide you through the process of writing and running component tests in Vue.js applications. Testing is a critical part of software development that ensures your code runs as expected and helps prevent bugs.
By the end of this tutorial, you will be able to:
- Understand the importance and principles of component testing in Vue.js
- Write tests for individual Vue components
- Run these tests to validate your components
Prerequisites:
- Basic understanding of Vue.js and JavaScript
- Vue CLI installed on your system
We'll be using Vue Test Utils, the official unit testing utility library for Vue.js. To install it, run the following command:
npm install --save @vue/test-utils
Consider a simple Vue component 'HelloWorld.vue':
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
To test this component, we will:
Here is a simple test for the HelloWorld component:
// import Vue and the component being tested
import Vue from 'vue'
import HelloWorld from '@/components/HelloWorld.vue'
import { mount } from '@vue/test-utils'
describe('HelloWorld.vue', () => {
it('is a Vue instance', () => {
const wrapper = mount(HelloWorld, {
propsData: {
msg: 'Hello Vue'
}
})
expect(wrapper.isVueInstance()).toBeTruthy()
})
})
it('renders props.msg when passed', () => {
const msg = 'new message'
const wrapper = mount(HelloWorld, {
propsData: { msg }
})
expect(wrapper.text()).toBe(msg)
})
This test asserts that when the msg
prop is passed to the component, it correctly renders the value in the component's template.
it('increments count when button is clicked', () => {
const wrapper = mount(Counter)
wrapper.find('button').trigger('click')
expect(wrapper.vm.count).toBe(1)
})
This test asserts that when the button in the Counter component is clicked, it increments the count
data property.
In this tutorial, we learned how to write and run component tests in Vue.js applications. We learned how to test the component output and user interactions.
Next, you might want to learn how to test Vue Router, Vuex and other Vue plugins. You can also write tests for your custom directives and filters.
Remember to run your tests after writing them to ensure they pass. Keep practicing and exploring different scenarios. Happy testing!