javascript / intermediate
Snippet
Asserting Custom Emitted Events and Payload Signatures in Component Unit Tests
Unit testing component communication requires verifying that child components correctly emit custom events with the expected payload structures. Vue Test Utils provides the emitted() helper method to inspect event names, invocation counts, and argument payloads.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { mount } from '@vue/test-utils';import StatusToggle from './StatusToggle.vue';describe('StatusToggle.vue', () => {it('emits state-change event with toggled boolean payload', async () => {const wrapper = mount(StatusToggle, {props: { initialActive: false }});await wrapper.find('button.toggle-btn').trigger('click');const emittedEvents = wrapper.emitted('state-change');expect(emittedEvents).toBeDefined();expect(emittedEvents).toHaveLength(1);expect(emittedEvents[0]).toEqual([{ active: true, timestamp: expect.any(Number) }]);});});
vue
Breakdown
1
const wrapper = mount(StatusToggle, {
Renders the component in an isolated test environment while providing mock initial properties.
2
await wrapper.find('button.toggle-btn').trigger('click');
Simulates a user click event asynchronously and awaits DOM and reactivity updates.
3
const emittedEvents = wrapper.emitted('state-change');
Retrieves the historical array of arguments captured for all occurrences of the specified custom event.
4
expect(emittedEvents[0]).toEqual([{ active: true, timestamp: expect.any(Number) }]);
Verifies that the first emitted event received an object containing the expected toggled state and payload types.