Unit Testing

Unit Testing Examples

Learn unit testing fundamentals with practical examples using Vitest and vitest-browser-svelte

Interactive Calculator

A working calculator with comprehensive unit tests

0

Test Coverage

Basic Operations
100%
Edge Cases
95%
Error Handling
90%

Testing Tools

Vitest
vitest-browser-svelte
User Events
Mock Functions

Testing Concepts

Arrange, Act, Assert

The fundamental pattern for structuring unit tests

Setup test data
Execute function
Verify results

Mocking

Isolate units by mocking dependencies

Mock functions
Mock modules
Spy on calls

Test Coverage

Measure and improve test coverage

Line coverage
Branch coverage
Function coverage

Code Examples

Basic Function Test

// calculator.test.ts
import { expect, test } from 'vitest';
import { add } from './calculator.js';

test('adds two numbers', () => {
  // Arrange
  const a = 2;
  const b = 3;
  
  // Act
  const result = add(a, b);
  
  // Assert
  expect(result).toBe(5);
});

Component Test

// button.svelte.test.ts
import { render } from 'vitest-browser-svelte';
import { page } from 'vitest-browser/context';
import { expect, test, vi } from 'vitest';
import Button from './button.svelte';

test('calls on_click when clicked', async () => {
  const on_click = vi.fn();
  render(Button, {
    props: { on_click }
  });
  
  const button = page.getByRole('button');
  await button.click();
  expect(on_click).toHaveBeenCalled();
});

Unit Testing Best Practices

Test Structure

  • • Use descriptive test names
  • • Follow AAA pattern
  • • One assertion per test
  • • Group related tests

Test Quality

  • • Test behavior, not implementation
  • • Use meaningful assertions
  • • Avoid test interdependence
  • • Keep tests simple

Coverage Goals

  • • Aim for 80%+ coverage
  • • Focus on critical paths
  • • Test edge cases
  • • Don't chase 100%

Explore More Examples

Continue learning with more advanced testing patterns