0
0
Svelteframework~5 mins

Unit testing logic in Svelte

Choose your learning style9 modes available
Introduction

Unit testing logic helps you check if small parts of your Svelte app work correctly. It finds mistakes early so your app stays reliable.

When you want to check if a function returns the right result.
When you change code and want to make sure nothing else breaks.
When you build a new feature and want to test its parts separately.
When you fix a bug and want to confirm the fix works.
When you want to write code that is easier to maintain and understand.
Syntax
Svelte
import { describe, it, expect } from 'vitest';

// Example test block
describe('functionName', () => {
  it('should do something', () => {
    expect(functionName(input)).toBe(expectedOutput);
  });
});

describe groups related tests together.

it defines a single test case.

Examples
This test checks if the add function returns the sum of two numbers.
Svelte
import { describe, it, expect } from 'vitest';

function add(a, b) {
  return a + b;
}

describe('add', () => {
  it('adds two numbers', () => {
    expect(add(2, 3)).toBe(5);
  });
});
This test checks if isEven correctly identifies even and odd numbers.
Svelte
import { describe, it, expect } from 'vitest';

function isEven(num) {
  return num % 2 === 0;
}

describe('isEven', () => {
  it('returns true for even numbers', () => {
    expect(isEven(4)).toBe(true);
  });
  it('returns false for odd numbers', () => {
    expect(isEven(3)).toBe(false);
  });
});
Sample Program

This example tests the greet function to make sure it returns a friendly greeting with the given name. It also tests what happens if the name is empty.

Svelte
import { describe, it, expect } from 'vitest';

// Simple function to test
function greet(name) {
  return `Hello, ${name}!`;
}

describe('greet function', () => {
  it('greets a person by name', () => {
    expect(greet('Alice')).toBe('Hello, Alice!');
  });
  it('greets with empty string if no name', () => {
    expect(greet('')).toBe('Hello, !');
  });
});
OutputSuccess
Important Notes

Use clear and simple test names to understand what each test checks.

Run tests often to catch problems early.

Tests should be independent; one test should not rely on another.

Summary

Unit tests check small parts of your code to catch errors early.

Use describe and it blocks to organize tests.

Write simple tests that are easy to read and maintain.