import React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; 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('has a Try Again button that attempts to reset', async () => { const user = userEvent.setup(); const onError = vi.fn(); render( ); // Error UI should be visible expect(screen.getByText('Something went wrong')).toBeInTheDocument(); expect(onError).toHaveBeenCalledTimes(1); // Try Again button should be present and clickable const tryAgainButton = screen.getByRole('button', { name: /try again/i }); expect(tryAgainButton).toBeInTheDocument(); // Clicking it will attempt to reset and re-render // Since our component still throws, it will catch the error again await user.click(tryAgainButton); // The error boundary catches the error again (expected behavior) expect(onError).toHaveBeenCalledTimes(2); }); it('shows action buttons in error state', () => { render( ); expect(screen.getByRole('button', { name: /try again/i })).toBeInTheDocument(); 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; }); });