What if a tiny mistake in your code silently ruins your app's core features?
Why Unit testing logic in Svelte? - Purpose & Use Cases
Imagine you write a function to calculate discounts for your online store. You change the code later, but you forget to check if it still works correctly everywhere.
Manually checking every possible input and output is slow, tiring, and easy to miss mistakes. Bugs can sneak in and break your app without you noticing.
Unit testing lets you write small automatic checks for your logic. These tests run quickly and tell you if something breaks right away.
function calculateDiscount(price) {
// manual checks needed every time
if (price > 100) return price * 0.9;
return price;
}
// Manually test with console logs or clicking buttonsimport { test, expect } from 'vitest'; function calculateDiscount(price) { if (price > 100) return price * 0.9; return price; } test('discount applies for price over 100', () => { expect(calculateDiscount(150)).toBe(135); }); // Tests run automatically and catch errors fast
Unit testing makes your code safer to change and helps you build features faster with confidence.
When adding a new payment method, unit tests ensure your discount logic still works without breaking the checkout process.
Manual checks are slow and error-prone.
Unit tests automatically verify your logic.
Tests help catch bugs early and save time.