import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen } from '@testing-library/react'; import { ErrorBoundary } from './ErrorBoundary'; // Component that throws an error function ThrowError({ shouldThrow }: { shouldThrow: boolean }) { if (shouldThrow) { throw new Error('Test error message'); } return
No error
; } describe('ErrorBoundary', () => { // Suppress console.error during tests to avoid noise const originalError = console.error; beforeEach(() => { console.error = vi.fn(); }); afterEach(() => { console.error = originalError; }); it('renders children when there is no error', () => { render(
Test content
); expect(screen.getByText('Test content')).toBeInTheDocument(); }); it('renders error UI when child component throws', () => { render( ); expect(screen.getByText('Something went wrong')).toBeInTheDocument(); expect(screen.getByText('Test error message')).toBeInTheDocument(); }); it('renders custom fallback when provided as ReactNode', () => { const customFallback =
Custom error UI
; render( ); expect(screen.getByText('Custom error UI')).toBeInTheDocument(); }); it('renders custom fallback when provided as function', () => { const customFallback = ({ error }: { error: Error }) => (
Error: {error.message}
); render( ); expect(screen.getByText('Error: Test error message')).toBeInTheDocument(); }); it('calls onError callback when error occurs', () => { const onError = vi.fn(); render( ); expect(onError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ componentStack: expect.any(String), }) ); }); it('shows action buttons in error state', () => { render( ); expect(screen.getByRole('button', { name: /reload page/i })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /go home/i })).toBeInTheDocument(); }); it('shows stack trace in development mode', () => { const originalEnv = process.env.NODE_ENV; process.env.NODE_ENV = 'development'; render( ); expect(screen.getByText('Stack Trace')).toBeInTheDocument(); process.env.NODE_ENV = originalEnv; }); });