Skip to content

Unit Testing

Unit tests verify individual functions, utilities, and components in isolation. They’re fast to run and easy to write.

lib/format.ts
export function formatDate(date: Date): string {
return new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}).format(date)
}
export function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1)
}
tests/format.test.ts
import { describe, it, expect } from 'vitest'
import { formatDate, capitalize } from '@/lib/format'
describe('formatDate', () => {
it('formats a date correctly', () => {
const date = new Date('2024-01-15')
expect(formatDate(date)).toBe('January 15, 2024')
})
})
describe('capitalize', () => {
it('capitalizes the first letter', () => {
expect(capitalize('hello')).toBe('Hello')
})
it('handles empty strings', () => {
expect(capitalize('')).toBe('')
})
})
components/Greeting.tsx
export function Greeting({ name }: { name: string }) {
return <h1>Hello, {name}!</h1>
}
tests/Greeting.test.tsx
import { render, screen } from '@testing-library/react'
import { Greeting } from '@/components/Greeting'
describe('Greeting', () => {
it('renders the name', () => {
render(<Greeting name="Alice" />)
expect(screen.getByText('Hello, Alice!')).toBeDefined()
})
})
Terminal window
# Run all tests
npx vitest
# Run with watch mode
npx vitest --watch
# Run once (CI)
npx vitest run
# Check coverage
npx vitest run --coverage
  • Testing implementation details — Test behavior, not internal state or methods.
  • Too many mocks — If you need to mock everything, the code might be too coupled.
  • Not testing edge cases — Empty strings, null values, error states.
  • Test behavior, not implementation
  • One assertion per test (or a few related ones)
  • Use descriptive test names that explain the expected behavior
  • Run tests on every commit (pre-commit hook or CI)

Unit tests verify individual functions and components. They’re fast and should run on every commit. Test behavior, not implementation. Cover edge cases and error states.