javascript / beginner
Snippet
Triggering Button Click Events with Vue Test Utils
Component unit tests verify that user interactions emit the expected events. Using trigger() from Vue Test Utils simulates a user click asynchronously, allowing assertions against the component's emitted events list.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
import { mount } from '@vue/test-utils';import CounterButton from './CounterButton.vue';import { test, expect } from 'vitest';test('emits increment event on button click', async () => {const wrapper = mount(CounterButton);const button = wrapper.find('button');await button.trigger('click');expect(wrapper.emitted()).toHaveProperty('increment');});
vue
Breakdown
1
const wrapper = mount(CounterButton);
Mounts the target Vue component into an isolated testing wrapper.
2
await button.trigger('click');
Simulates a user click event and awaits the DOM and reactivity updates.
3
expect(wrapper.emitted()).toHaveProperty('increment');
Asserts that the component successfully emitted the 'increment' custom event.