Using Vue.js with a testing library like Vue Test Utils is a great way to ensure the reliability and functionality of your Vue components. Vue Test Utils is an official library for testing Vue components. Here's a step-by-step guide on how to use Vue Test Utils with Vue.js:
bashnpm install @vue/test-utils --save-dev
or
bashyarn add @vue/test-utils --dev
MyComponent.vue
, create a test file named MyComponent.spec.js
:javascript// MyComponent.spec.js
import { mount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
describe('MyComponent', () => {
it('renders correctly', () => {
const wrapper = mount(MyComponent)
expect(wrapper.html()).toMatchSnapshot()
})
it('has a button that triggers a function', async () => {
const wrapper = mount(MyComponent)
const button = wrapper.find('button')
await button.trigger('click')
expect(wrapper.vm.clicked).toBe(true)
})
})
Mount the component: Use mount
from Vue Test Utils to mount your Vue component. This allows you to interact with and test the rendered component.
Interact with the component: Use various methods provided by Vue Test Utils to interact with the mounted component. For example, you can find elements within the component using wrapper.find()
, trigger events on elements using trigger()
, and assert the component's state and properties.
Run your tests: Once you've written your tests, run them using your chosen test runner. If you're using Jest, you can run your tests with npm test
or yarn test
.
By following these steps, you can effectively use Vue Test Utils to test your Vue.js components, ensuring that they behave as expected and catch any potential bugs early in the development process.