Unit Testing
VitestTest individual functions, hooks, and utilities in isolation.
Overview
Unit tests verify that individual pieces of code work correctly in isolation. Oorty generates unit tests for your utility functions, custom hooks, and pure functions using Vitest.
Run thousands of unit tests in seconds with Vitest's native ESM support.
Oorty sets up intelligent mocks for external dependencies automatically.
Built-in V8 coverage with detailed reports out of the box.
Writing Unit Tests
Place unit tests in __tests__/unit/ directory.
Testing Utility Functions
// lib/utils/format.tsexport function formatCurrency( amount: number, currency: string = 'USD'): string { return new Intl.NumberFormat('en-US', { style: 'currency', currency, }).format(amount)}export function formatDate( date: Date | string, options?: Intl.DateTimeFormatOptions): string { const d = typeof date === 'string' ? new Date(date) : date return d.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', ...options, })}export function slugify(text: string): string { return text .toLowerCase() .trim() .replace(/[^\w\s-]/g, '') .replace(/[\s_-]+/g, '-') .replace(/^-+|-+$/g, '')}Testing Custom Hooks
// hooks/use-local-storage.tsimport { useState, useEffect } from 'react'export function useLocalStorage( key: string, initialValue: T): [T, (value: T) => void] { const [storedValue, setStoredValue] = useState(() => { if (typeof window === 'undefined') { return initialValue } try { const item = window.localStorage.getItem(key) return item ? JSON.parse(item) : initialValue } catch (error) { console.error(error) return initialValue } }) const setValue = (value: T) => { try { setStoredValue(value) if (typeof window !== 'undefined') { window.localStorage.setItem(key, JSON.stringify(value)) } } catch (error) { console.error(error) } } return [storedValue, setValue]}Running Unit Tests
# Run all unit testsnpm run test:unit# Run in watch modenpm run test:unit -- --watch# Run with coverage (Vitest reporters from vitest.config)npm run test:unit -- --coverage# Or use the Oorty helper (same engine; see docs/cli/coverage)npx oorty coverage# Run specific test filenpm run test:unit -- format.test.tsBest Practices
Test one thing per test
Each test should verify a single behavior. This makes tests easier to understand and debug.
Use descriptive names
Test names should describe the expected behavior: "formats negative numbers correctly" is better than "test negative".
Avoid testing implementation details
Focus on inputs and outputs, not how the function achieves the result internally.
Keep tests independent
Tests should not depend on each other or on shared mutable state. Use beforeEach for setup.