0
0
Vueframework~30 mins

Component testing with Vue Test Utils - Mini Project: Build & Apply

Choose your learning style9 modes available
Component testing with Vue Test Utils
📖 Scenario: You are building a simple Vue component that shows a greeting message. You want to write tests to check if the component renders the message correctly and updates it when a button is clicked.
🎯 Goal: Create a Vue component called GreetingMessage that displays a message from a prop. Then write tests using Vue Test Utils to check the rendered output and simulate a button click to change the message.
📋 What You'll Learn
Create a Vue component with a message prop
Render the message prop inside a <p> tag
Add a button that changes the message when clicked
Write a test to check the initial rendered message
Write a test to simulate the button click and check the updated message
💡 Why This Matters
🌍 Real World
Testing Vue components ensures your UI works as expected before users see it. It helps catch bugs early and improves code quality.
💼 Career
Vue Test Utils is a common tool used by frontend developers to write unit tests for Vue components, a key skill in many web development jobs.
Progress0 / 4 steps
1
Create the GreetingMessage component with a message prop
Create a Vue component called GreetingMessage using <script setup>. Define a prop named message of type String. Render the message prop inside a <p> tag.
Vue
Hint

Use defineProps to declare the message prop and display it inside a <p> tag in the template.

2
Add a button to change the message
Inside the GreetingMessage component, add a ref variable called currentMessage initialized with the message prop. Add a button with text Change Message. When the button is clicked, update currentMessage to the string 'Hello Vue Test Utils!'. Render currentMessage inside the <p> tag instead of props.message.
Vue
Hint

Use ref to create a reactive variable currentMessage. Add a button with a click event handler that updates currentMessage.

3
Write a test to check the initial rendered message
Create a test file for GreetingMessage. Import mount from @vue/test-utils and the GreetingMessage component. Write a test named 'renders initial message' that mounts GreetingMessage with the prop message set to 'Hello Vue!'. Use wrapper.text() to check that the rendered text contains 'Hello Vue!'.
Vue
Hint

Use mount to create a wrapper of the component with the message prop. Then check the text content with wrapper.text().

4
Write a test to simulate button click and check updated message
In the test file, write a test named 'updates message on button click'. Mount GreetingMessage with the prop message set to 'Hello Vue!'. Use wrapper.find('button') to get the button and call trigger('click') on it. Then check that wrapper.text() contains 'Hello Vue Test Utils!'.
Vue
Hint

Use find to get the button element and trigger('click') to simulate the click. Then check the updated text.