File size: 1,886 Bytes
f0743f4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import SourcesErrorBoundary from '../SourcesErrorBoundary';
// Component that throws an error for testing
const ThrowError = ({ shouldThrow }: { shouldThrow: boolean }) => {
if (shouldThrow) {
throw new Error('Test error');
}
return <div data-testid="normal-component">{'Normal component'}</div>;
};
// Mock window.location.reload
const mockReload = jest.fn();
Object.defineProperty(window, 'location', {
value: {
reload: mockReload,
},
writable: true,
});
describe('SourcesErrorBoundary - NEW COMPONENT test', () => {
beforeEach(() => {
jest.clearAllMocks();
// Suppress error console logs during tests
jest.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
jest.restoreAllMocks();
});
it('should render children when there is no error', () => {
render(
<SourcesErrorBoundary>
<ThrowError shouldThrow={false} />
</SourcesErrorBoundary>,
);
expect(screen.getByTestId('normal-component')).toBeInTheDocument();
});
it('should render default error UI when error occurs', () => {
render(
<SourcesErrorBoundary>
<ThrowError shouldThrow={true} />
</SourcesErrorBoundary>,
);
expect(screen.getByText('Sources temporarily unavailable')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Reload the page' })).toBeInTheDocument();
});
it('should reload page when refresh button is clicked', () => {
render(
<SourcesErrorBoundary>
<ThrowError shouldThrow={true} />
</SourcesErrorBoundary>,
);
const refreshButton = screen.getByRole('button', { name: 'Reload the page' });
fireEvent.click(refreshButton);
expect(mockReload).toHaveBeenCalled();
});
});
|