0 day streak
javascript / intermediate
Snippet

Asserting Emitted Component Events with Vue Test Utils

Testing component contracts involves verifying that user interactions trigger expected custom events with accurate arguments. Vue Test Utils provides the `emitted()` API, which captures all events dispatched during the component lifecycle. By awaiting DOM triggers, tests ensure microtasks and reactive watchers flush before asserting emitted payloads.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { mount } from '@vue/test-utils';
import CounterButton from './CounterButton.vue';
describe('CounterButton', () => {
it('emits increment payload on user click', async () => {
const wrapper = mount(CounterButton, {
props: { step: 5 }
});
await wrapper.find('button').trigger('click');
const emittedEvents = wrapper.emitted('increment');
expect(emittedEvents).toHaveLength(1);
expect(emittedEvents[0]).toEqual([5]);
});
});
vue
Breakdown
1
const wrapper = mount(CounterButton, {
Mounts the target Vue component in an isolated virtual DOM environment with specified initial props.
2
await wrapper.find('button').trigger('click');
Locates the button element and simulates a click event, awaiting the subsequent DOM and reactivity update cycle.
3
const emittedEvents = wrapper.emitted('increment');
Retrieves the historical array of all emissions registered for the 'increment' event name.
4
expect(emittedEvents[0]).toEqual([5]);
Asserts that the first event emission contains the expected array of arguments payload.