0
0
VueHow-ToBeginner · 3 min read

How to Test Events in Vue: Simple Guide with Examples

To test events in Vue, use Vue Test Utils to mount the component and trigger events with wrapper.trigger(). Then, check if the event was emitted using wrapper.emitted() to confirm the event fired correctly.
📐

Syntax

Use wrapper.trigger(eventName) to simulate an event on a component or element. Then use wrapper.emitted() to check which events were emitted and their payloads.

Parts explained:

  • wrapper: The mounted Vue component wrapper.
  • trigger(eventName): Simulates the event like 'click', 'input', etc.
  • emitted(): Returns an object with event names as keys and arrays of payloads as values.
javascript
const wrapper = mount(MyComponent)
await wrapper.trigger('click')
expect(wrapper.emitted('my-event')).toBeTruthy()
💻

Example

This example shows a button component that emits a submit event when clicked. The test mounts the component, triggers a click, and checks the event was emitted once.

javascript
import { mount } from '@vue/test-utils'
import { defineComponent, h } from 'vue'

const Button = defineComponent({
  emits: ['submit'],
  setup(props, { emit }) {
    const onClick = () => emit('submit')
    return () => h('button', { onClick }, 'Submit')
  }
})

test('emits submit event on click', async () => {
  const wrapper = mount(Button)
  await wrapper.trigger('click')
  expect(wrapper.emitted('submit')).toHaveLength(1)
})
Output
PASS emits submit event on click
⚠️

Common Pitfalls

1. Forgetting to use await with trigger: Events may not be processed before assertions, causing false negatives.

2. Checking wrong event name: Event names are case-sensitive and must match exactly.

3. Not mounting the component properly: Without mounting, wrapper is undefined and tests fail.

javascript
/* Wrong: Missing await */
const wrapper = mount(Button)
wrapper.trigger('click')
expect(wrapper.emitted('submit')).toHaveLength(1) // May fail

/* Right: Use await */
await wrapper.trigger('click')
expect(wrapper.emitted('submit')).toHaveLength(1)
📊

Quick Reference

MethodPurpose
mount(component)Creates a wrapper to test the component
wrapper.trigger(eventName)Simulates an event on the component or element
wrapper.emitted()Returns all emitted events with their payloads
wrapper.emitted(eventName)Returns array of payloads for a specific event
await wrapper.trigger(eventName)Waits for event and DOM updates before assertions

Key Takeaways

Use Vue Test Utils' mount and trigger to simulate events in Vue components.
Always await wrapper.trigger() to ensure event processing before assertions.
Check emitted events with wrapper.emitted() to verify event firing and payloads.
Event names are case-sensitive and must match exactly in tests.
Properly mount components before testing events to avoid errors.