0
0
Svelteframework~30 mins

Unit testing logic in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Unit Testing Logic in Svelte
📖 Scenario: You are building a simple Svelte component that shows a message based on a number. You want to write unit tests to check the logic that decides which message to show.
🎯 Goal: Create a Svelte component with a number variable and a function that returns a message based on that number. Then write unit tests to check the function's logic.
📋 What You'll Learn
Create a Svelte component with a number variable set to 10
Add a function getMessage that returns 'High' if number > 50, else 'Low'
Write a unit test to check getMessage returns 'Low' when number is 10
Write a unit test to check getMessage returns 'High' when number is 60
💡 Why This Matters
🌍 Real World
Unit testing logic in components helps catch bugs early and ensures your app behaves as expected.
💼 Career
Writing unit tests is a key skill for frontend developers to maintain reliable and maintainable codebases.
Progress0 / 4 steps
1
Create the Svelte component with a number variable
Create a Svelte component file with a number variable set to 10 inside a <script> tag.
Svelte
Hint

Use let number = 10; inside the <script> tag.

2
Add the getMessage function to decide the message
Inside the <script> tag, add a function called getMessage that returns 'High' if number > 50, otherwise returns 'Low'.
Svelte
Hint

Use a ternary operator inside the function to return the correct string.

3
Write a unit test for getMessage returning 'Low' when number is 10
Create a test file and write a unit test that sets number to 10 and checks that getMessage() returns 'Low'.
Svelte
Hint

Use vitest to write the test with describe, it, and expect.

4
Write a unit test for getMessage returning 'High' when number is 60
Add another unit test that sets number to 60 and checks that getMessage() returns 'High'.
Svelte
Hint

Add a new it block inside the describe to test the 'High' case.