5 min read
•Question 34 of 37mediumHow to test Vue components?
Unit testing with Vue Test Utils.
What You'll Learn
- Vue Test Utils setup
- Mounting components
- Testing interactions
Setup with Vitest
$ terminalBash
npm install -D vitest @vue/test-utilsBasic Test
code.jsJavaScript
import { mount } from '@vue/test-utils'
import Counter from './Counter.vue'
test('increments count', async () => {
const wrapper = mount(Counter)
expect(wrapper.text()).toContain('0')
await wrapper.find('button').trigger('click')
expect(wrapper.text()).toContain('1')
})Testing Props
code.jsJavaScript
test('renders title prop', () => {
const wrapper = mount(MyComponent, {
props: { title: 'Hello' }
})
expect(wrapper.text()).toContain('Hello')
})Testing Emits
code.jsJavaScript
test('emits event on click', async () => {
const wrapper = mount(MyComponent)
await wrapper.find('button').trigger('click')
expect(wrapper.emitted('submit')).toBeTruthy()
expect(wrapper.emitted('submit')[0]).toEqual(['data'])
})Testing with Pinia
code.jsJavaScript
import { setActivePinia, createPinia } from 'pinia'
beforeEach(() => {
setActivePinia(createPinia())
})
test('uses store', () => {
const wrapper = mount(MyComponent)
// ...
})