diff --git a/src/components/ui/Popover/tests/Popover.portal.test.tsx b/src/components/ui/Popover/tests/Popover.portal.test.tsx new file mode 100644 index 000000000..d072aa769 --- /dev/null +++ b/src/components/ui/Popover/tests/Popover.portal.test.tsx @@ -0,0 +1,44 @@ +import React from 'react'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import Popover from '../Popover'; +import Theme from '~/components/ui/Theme/Theme'; + +const mockMatchMedia = () => { + if ('matchMedia' in window && typeof window.matchMedia === 'function') return; + Object.defineProperty(window, 'matchMedia', { + writable: true, + value: jest.fn().mockImplementation(() => ({ + matches: false, + addEventListener: jest.fn(), + removeEventListener: jest.fn() + })) + }); +}; + +describe('Popover primitive portal', () => { + beforeEach(() => mockMatchMedia()); + + test('portals content into Theme portal root', async() => { + const user = userEvent.setup(); + + render( + + + Open + + Portaled popover + + + + ); + + const portalRoot = document.querySelector('[data-rad-ui-portal-root]') as HTMLElement; + expect(portalRoot).toBeTruthy(); + + await user.click(screen.getByText('Open')); + await waitFor(() => { + expect(portalRoot).toContainElement(screen.getByText('Portaled popover')); + }); + }); +}); diff --git a/src/core/primitives/Popover/fragments/PopoverPrimitivePortal.tsx b/src/core/primitives/Popover/fragments/PopoverPrimitivePortal.tsx index 617ad7221..63696b94b 100644 --- a/src/core/primitives/Popover/fragments/PopoverPrimitivePortal.tsx +++ b/src/core/primitives/Popover/fragments/PopoverPrimitivePortal.tsx @@ -21,12 +21,10 @@ const PopoverPrimitivePortal = ({ const [isMounted, setIsMounted] = React.useState(false); React.useEffect(() => { - rootElementRef.current = (container as HTMLElement | null) || - themeContext?.portalRootRef.current || - document.querySelector('[data-rad-ui-portal-root]') as HTMLElement | null || - themeContext?.containerRef.current || - document.querySelector('#rad-ui-theme-container') as HTMLElement | null || - document.body; + rootElementRef.current = (container as HTMLElement | null) + ?? themeContext?.portalRootRef.current + ?? themeContext?.containerRef.current + ?? document.body; setIsMounted(true); }, [container, themeContext]);