diff --git a/packages/sanity/src/core/form/studio/FormBuilderInputErrorBoundary.test.tsx b/packages/sanity/src/core/form/studio/FormBuilderInputErrorBoundary.test.tsx new file mode 100644 index 00000000000..dfb64748038 --- /dev/null +++ b/packages/sanity/src/core/form/studio/FormBuilderInputErrorBoundary.test.tsx @@ -0,0 +1,69 @@ +import {beforeAll, describe, expect, it, jest} from '@jest/globals' +import {studioTheme, ThemeProvider} from '@sanity/ui' +import {render, screen} from '@testing-library/react' + +import {LocaleProviderBase} from '../../i18n/components/LocaleProvider' +import {prepareI18n} from '../../i18n/i18nConfig' +import {usEnglishLocale} from '../../i18n/locales' +import {useSource} from '../../studio/source' +import {FormBuilderInputErrorBoundary} from './FormBuilderInputErrorBoundary' + +// Mock dependencies +jest.mock('../../studio/source', () => ({ + useSource: jest.fn(), +})) + +jest.mock('use-hot-module-reload', () => ({ + useHotModuleReload: jest.fn(), +})) + +const useSourceMock = useSource as jest.Mock + +describe('FormBuilderInputErrorBoundary', () => { + beforeAll(() => { + jest.clearAllMocks() + }) + + it('renders children when there is no error', async () => { + render( + +
Child Component
+
, + ) + + expect(screen.getByTestId('child')).toBeInTheDocument() + }) + + it('calls onStudioError when an error is caught', async () => { + const onStudioError = jest.fn() + useSourceMock.mockReturnValue({onStudioError}) + + const ThrowErrorComponent = () => { + throw new Error('An EXPECTED, testing error occurred!') + } + + const locales = [usEnglishLocale] + const {i18next} = prepareI18n({ + projectId: 'test', + dataset: 'test', + name: 'test', + }) + + render( + + + + + + + , + ) + + expect(onStudioError).toHaveBeenCalledTimes(1) + }) +}) diff --git a/packages/sanity/src/core/form/studio/FormBuilderInputErrorBoundary.tsx b/packages/sanity/src/core/form/studio/FormBuilderInputErrorBoundary.tsx index 1220ce83578..e2b3dafed48 100644 --- a/packages/sanity/src/core/form/studio/FormBuilderInputErrorBoundary.tsx +++ b/packages/sanity/src/core/form/studio/FormBuilderInputErrorBoundary.tsx @@ -28,17 +28,18 @@ export function FormBuilderInputErrorBoundary( error: null, info: {}, }) - const {onStudioError} = useSource() + const source = useSource() const handleRetry = useCallback(() => setError({error: null, info: {}}), []) const handleCatch = useCallback( ({error: caughtError, info: caughtInfo}: {error: Error; info: React.ErrorInfo}) => { setError({error: caughtError, info: caughtInfo}) - if (onStudioError) { + if (source?.onStudioError) { + const {onStudioError} = source onStudioError(caughtError, caughtInfo) } }, - [onStudioError], + [source], ) if (!error) {