Voeg Sentry-foutregistratie toe als gekozen logging-bestemming
Co-authored-by: Junie <junie@jetbrains.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { Component } from 'react';
|
||||
import type { ErrorInfo, ReactNode } from 'react';
|
||||
import * as Sentry from '@sentry/react';
|
||||
|
||||
interface ErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
@@ -22,6 +23,7 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
|
||||
|
||||
componentDidCatch(error: Error, info: ErrorInfo): void {
|
||||
console.error('Unexpected application error', error, info);
|
||||
Sentry.captureException(error, { extra: { componentStack: info.componentStack } });
|
||||
}
|
||||
|
||||
render(): ReactNode {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { ErrorBoundary } from '../ErrorBoundary';
|
||||
|
||||
vi.mock('@sentry/react', () => ({
|
||||
captureException: vi.fn(),
|
||||
}));
|
||||
|
||||
function ThrowingChild(): never {
|
||||
throw new Error('boom');
|
||||
}
|
||||
|
||||
describe('ErrorBoundary', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders children when there is no error', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<p>Alles werkt</p>
|
||||
</ErrorBoundary>,
|
||||
);
|
||||
expect(screen.getByText('Alles werkt')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the generic fallback message when a child throws', () => {
|
||||
// Suppress the expected React error boundary console.error noise for this test.
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ThrowingChild />
|
||||
</ErrorBoundary>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('error-boundary-fallback')).toBeInTheDocument();
|
||||
expect(screen.getByText('Er ging iets mis. Probeer de pagina te vernieuwen.')).toBeInTheDocument();
|
||||
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('reports the caught error to Sentry', () => {
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ThrowingChild />
|
||||
</ErrorBoundary>,
|
||||
);
|
||||
|
||||
expect(Sentry.captureException).toHaveBeenCalledTimes(1);
|
||||
expect(Sentry.captureException).toHaveBeenCalledWith(
|
||||
expect.any(Error),
|
||||
expect.objectContaining({ extra: expect.objectContaining({ componentStack: expect.any(String) }) }),
|
||||
);
|
||||
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user