diff --git a/src/components/ui/AlertDialog/tests/AlertDialog.controlledSwitch.test.tsx b/src/components/ui/AlertDialog/tests/AlertDialog.controlledSwitch.test.tsx new file mode 100644 index 000000000..b1a2c078e --- /dev/null +++ b/src/components/ui/AlertDialog/tests/AlertDialog.controlledSwitch.test.tsx @@ -0,0 +1,82 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import AlertDialog from '../AlertDialog'; + +describe('AlertDialog controlled/uncontrolled mode switching', () => { + test('switches from uncontrolled to controlled', async() => { + const user = userEvent.setup(); + const onOpenChange = jest.fn(); + + const { rerender } = render( + + Open + + Alert content + + + ); + + await user.click(screen.getByText('Open')); + expect(screen.getByText('Alert content')).toBeInTheDocument(); + + rerender( + + Open + + Alert content + + + ); + + expect(screen.queryByText('Alert content')).not.toBeInTheDocument(); + await user.click(screen.getByText('Open')); + expect(onOpenChange).toHaveBeenCalledWith(true); + }); + + test('switches from controlled to uncontrolled', async() => { + const user = userEvent.setup(); + + const { rerender } = render( + {}}> + Open + + Alert content + + + ); + + expect(screen.getByText('Alert content')).toBeInTheDocument(); + + rerender( + + Open + + Alert content + + + ); + + expect(screen.queryByText('Alert content')).not.toBeInTheDocument(); + await user.click(screen.getByText('Open')); + expect(screen.getByText('Alert content')).toBeInTheDocument(); + }); + + test('closes without onOpenChange callback', async() => { + const user = userEvent.setup(); + + render( + + Open + + + Cancel + + + + ); + + await user.click(screen.getByText('Cancel')); + expect(screen.queryByText('Cancel')).not.toBeInTheDocument(); + }); +}); diff --git a/src/core/primitives/Dialog/fragments/DialogPrimitiveRoot.tsx b/src/core/primitives/Dialog/fragments/DialogPrimitiveRoot.tsx index 3a73463ce..2fd240a12 100644 --- a/src/core/primitives/Dialog/fragments/DialogPrimitiveRoot.tsx +++ b/src/core/primitives/Dialog/fragments/DialogPrimitiveRoot.tsx @@ -26,7 +26,7 @@ const DialogPrimitiveRootInner = forwardRef { setIsOpen(open); - onOpenChange(open); + onOpenChange?.(open); }; const handleOverlayClick = () => { if (disablePointerDismissal) return;