0
0
Svelteframework~30 mins

Component testing with Testing Library in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Component testing with Testing Library in Svelte
📖 Scenario: You are building a simple Svelte component that shows a greeting message and a button to change the greeting. You want to write tests to check that the component behaves correctly when the button is clicked.
🎯 Goal: Create a Svelte component called Greeting.svelte with a greeting message and a button. Then write tests using Testing Library to verify the initial message and the message after clicking the button.
📋 What You'll Learn
Create a Svelte component with a greeting message and a button
Add a variable to hold the greeting text
Write a test to check the initial greeting message
Write a test to check the greeting message after clicking the button
💡 Why This Matters
🌍 Real World
Testing components ensures your app works correctly when users interact with it, preventing bugs and improving quality.
💼 Career
Component testing with Testing Library is a common skill for frontend developers working with Svelte or other frameworks to deliver reliable user interfaces.
Progress0 / 4 steps
1
Create the Greeting component with initial message
Create a Svelte component file called Greeting.svelte. Inside it, declare a variable called greeting with the value "Hello, world!". Then add a <p> tag that displays the greeting variable.
Svelte
Hint

Use let greeting = "Hello, world!"; inside the <script> tag and display it inside a <p> tag.

2
Add a button to change the greeting
In Greeting.svelte, add a <button> element with the text Change Greeting. Add a click event handler that changes the greeting variable to "Hello, Svelte!" when the button is clicked.
Svelte
Hint

Define a function changeGreeting that sets greeting to "Hello, Svelte!". Attach it to the button's on:click event.

3
Write a test for the initial greeting message
Create a test file called Greeting.test.js. Import render and fireEvent from @testing-library/svelte and import the Greeting component. Write a test named "shows initial greeting" that renders Greeting and checks that the text "Hello, world!" is in the document.
Svelte
Hint

Use render(Greeting) and getByText('Hello, world!') to check the initial message.

4
Write a test for greeting change on button click
In Greeting.test.js, add a test named "changes greeting on button click". Render the Greeting component. Use getByText to find the button with text "Change Greeting". Use fireEvent.click on the button. Then check that the text "Hello, Svelte!" is now in the document.
Svelte
Hint

Find the button with getByText('Change Greeting'), click it with fireEvent.click, then check for 'Hello, Svelte!'.