javascript / beginner
Snippet
Testing Custom Event Emission in Vue
Component interaction tests verify that user actions like button clicks trigger the expected custom event emissions with the correct payload and frequency using wrapper.emitted().
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
import { mount } from '@vue/test-utils';import { expect, test } from 'vitest';import ActionButton from './ActionButton.vue';test('emits submit event upon button click', async () => {const wrapper = mount(ActionButton);await wrapper.find('button').trigger('click');expect(wrapper.emitted()).toHaveProperty('submit');expect(wrapper.emitted().submit).toHaveLength(1);});
vue
Breakdown
1
await wrapper.find('button').trigger('click');
Finds the button DOM node and simulates a user click asynchronously.
2
expect(wrapper.emitted()).toHaveProperty('submit');
Checks that the component registered an event emission named 'submit'.
3
expect(wrapper.emitted().submit).toHaveLength(1);
Verifies that the 'submit' event was emitted exactly one time during the interaction.