import React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, fireEvent } from '@testing-library/react'; import { ErrorBoundary } from '../ErrorBoundary'; // Helper component that throws an error during rendering const ProblemChild = ({ shouldThrow = true }: { shouldThrow?: boolean }) => { if (shouldThrow) { throw new Error('Test render crash'); } return
محتوای سالم کامپوننت
; }; describe('ErrorBoundary Component', () => { let consoleErrorSpy: any; beforeEach(() => { vi.clearAllMocks(); consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); }); afterEach(() => { consoleErrorSpy.mockRestore(); }); it('renders children normally when there is no error', () => { render( ); expect(screen.getByText('محتوای سالم کامپوننت')).toBeInTheDocument(); expect(screen.queryByText('متأسفانه خطایی رخ داده است')).not.toBeInTheDocument(); }); it('catches render errors and displays fallback UI', () => { render( ); expect(screen.getByText('متأسفانه خطایی رخ داده است')).toBeInTheDocument(); expect( screen.getByText('مشکلی در بارگذاری این بخش پیش آمده است. لطفاً برای ادامه دوباره تلاش کنید.') ).toBeInTheDocument(); expect(screen.getByRole('button', { name: /تلاش مجدد/ })).toBeInTheDocument(); expect(screen.getByText('Canina Pharma Support')).toBeInTheDocument(); expect(screen.queryByText('محتوای سالم کامپوننت')).not.toBeInTheDocument(); }); it('logs the uncaught error to console.error via componentDidCatch', () => { render( ); expect(consoleErrorSpy).toHaveBeenCalled(); }); it('triggers window.location.reload when reload/retry button is clicked', () => { const originalLocation = window.location; const reloadMock = vi.fn(); // Mock window.location.reload Object.defineProperty(window, 'location', { configurable: true, value: { ...originalLocation, reload: reloadMock, }, }); render( ); const retryButton = screen.getByRole('button', { name: /تلاش مجدد/ }); fireEvent.click(retryButton); expect(reloadMock).toHaveBeenCalledTimes(1); // Restore original location Object.defineProperty(window, 'location', { configurable: true, value: originalLocation, }); }); });