0
0
Vueframework~30 mins

Testing props and events in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing props and events
📖 Scenario: You are building a simple Vue component that shows a message and lets users click a button to notify the parent component.
🎯 Goal: Create a Vue component called MessageButton that accepts a message prop and emits a clicked event when the button is pressed. Then write tests to check the prop and event behavior.
📋 What You'll Learn
Create a Vue component named MessageButton with a message prop of type String
Render the message prop inside a <p> tag
Add a button that emits a clicked event when clicked
Write a test to check the message prop is rendered correctly
Write a test to check the clicked event is emitted on button click
💡 Why This Matters
🌍 Real World
Testing props and events is essential when building interactive Vue components to ensure they behave correctly and communicate with parent components.
💼 Career
Vue developers often write unit tests to verify component inputs (props) and outputs (events), which helps maintain reliable and bug-free applications.
Progress0 / 4 steps
1
Create the MessageButton component with a message prop
Create a Vue component named MessageButton using <script setup>. Define a prop called message of type String. Render the message prop inside a <p> tag.
Vue
Hint

Use defineProps to declare the message prop as a String. Then display it inside a paragraph tag.

2
Add a button that emits a clicked event
Add a button inside the MessageButton component template. When the button is clicked, emit a clicked event using defineEmits.
Vue
Hint

Use defineEmits to declare the clicked event. Add a button with a click handler that calls emit('clicked').

3
Write a test to check the message prop rendering
Write a test using @vue/test-utils to mount the MessageButton component with the message prop set to 'Hello Vue'. Assert that the rendered paragraph contains the text 'Hello Vue'.
Vue
Hint

Use mount to create the component with the message prop. Then check the paragraph text with wrapper.find('p').text().

4
Write a test to check the clicked event emission
Write a test using @vue/test-utils to mount the MessageButton component. Simulate a click on the button and assert that the clicked event was emitted once.
Vue
Hint

Use wrapper.find('button').trigger('click') to simulate the click. Then check wrapper.emitted('clicked') length is 1.