0
0
Vueframework~5 mins

Testing props and events in Vue

Choose your learning style9 modes available
Introduction

We test props and events to make sure components get the right data and communicate correctly.

When you want to check if a component shows the data passed to it.
When you want to verify a component sends the right event after a user action.
When you want to catch bugs early by testing component behavior.
When you want to ensure your app parts work well together.
When you want to keep your code safe during changes.
Syntax
Vue
import { mount } from '@vue/test-utils'

const wrapper = mount(Component, {
  props: { propName: value }
})

wrapper.vm.$emit('eventName', eventData)

expect(wrapper.props('propName')).toBe(value)
expect(wrapper.emitted('eventName')).toBeTruthy()

Use mount to create a test instance of your component.

Check props with wrapper.props() and events with wrapper.emitted().

Examples
This checks if the label prop is passed correctly to the MyButton component.
Vue
const wrapper = mount(MyButton, {
  props: { label: 'Click me' }
})
expect(wrapper.props('label')).toBe('Click me')
This tests if clicking the button triggers the click event.
Vue
await wrapper.find('button').trigger('click')
expect(wrapper.emitted('click')).toBeTruthy()
This verifies the submit event was emitted with the correct data.
Vue
expect(wrapper.emitted('submit')[0]).toEqual([{ name: 'John' }])
Sample Program

This component shows a button with a name prop. When clicked, it emits a greet event with a message. The test checks the prop and event.

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

const Greeting = defineComponent({
  props: { name: String },
  emits: ['greet'],
  setup(props, { emit }) {
    const sayHello = () => emit('greet', `Hello, ${props.name}!`)
    return () => h('button', { onClick: sayHello }, `Greet ${props.name}`)
  }
})

// Test
const wrapper = mount(Greeting, { props: { name: 'Alice' } })

// Check prop
console.log(wrapper.props('name'))

// Trigger event
wrapper.find('button').trigger('click')

// Check event
console.log(wrapper.emitted('greet'))
OutputSuccess
Important Notes

Always test both props and events to cover input and output of components.

Use await with trigger if your event handler is async.

Check event payloads carefully to ensure correct data is sent.

Summary

Props pass data into components; test them to confirm correct values.

Events send messages out; test them to confirm correct triggers and data.

Use Vue Test Utils mount, props(), and emitted() for easy testing.