Command Palette

Search for a command to run...

Unit Testing

Vitest

Test 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.

Fast Execution

Run thousands of unit tests in seconds with Vitest's native ESM support.

Smart Mocking

Oorty sets up intelligent mocks for external dependencies automatically.

Coverage Reports

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.ts
// lib/utils/format.ts
export 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.ts
// hooks/use-local-storage.ts
import { 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

Terminal
# Run all unit tests
npm run test:unit
# Run in watch mode
npm 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 file
npm run test:unit -- format.test.ts

Best 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.