diff --git a/.changeset/blue-moons-impress.md b/.changeset/blue-moons-impress.md new file mode 100644 index 0000000..e1fac5b --- /dev/null +++ b/.changeset/blue-moons-impress.md @@ -0,0 +1,5 @@ +--- +'react-collapsed': patch +--- + +Do not call window.matchMedia if it does not exist. Fixes errors thrown in environments like JSDOM. diff --git a/packages/react-collapsed/src/utils/usePrefersReducedMotion.ts b/packages/react-collapsed/src/utils/usePrefersReducedMotion.ts index ff5ead2..ae5675b 100644 --- a/packages/react-collapsed/src/utils/usePrefersReducedMotion.ts +++ b/packages/react-collapsed/src/utils/usePrefersReducedMotion.ts @@ -6,6 +6,10 @@ export function usePrefersReducedMotion() { const [prefersReducedMotion, setPrefersReducedMotion] = useState(false) useEffect(() => { + if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') { + return + } + const mediaQueryList = window.matchMedia(QUERY) // Set the true initial value, now that we're on the client: setPrefersReducedMotion(mediaQueryList.matches) diff --git a/packages/react-collapsed/tests/index.test.tsx b/packages/react-collapsed/tests/index.test.tsx index 64f7444..bf3990e 100644 --- a/packages/react-collapsed/tests/index.test.tsx +++ b/packages/react-collapsed/tests/index.test.tsx @@ -2,21 +2,6 @@ import * as React from 'react' import { render, fireEvent, screen } from '@testing-library/react' import { useCollapse } from '../src' -// https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom -Object.defineProperty(window, 'matchMedia', { - writable: true, - value: jest.fn().mockImplementation((query) => ({ - matches: false, - media: query, - onchange: null, - addListener: jest.fn(), // deprecated - removeListener: jest.fn(), // deprecated - addEventListener: jest.fn(), - removeEventListener: jest.fn(), - dispatchEvent: jest.fn(), - })), -}) - const Collapse = ({ toggleElement: Toggle = 'div', collapseProps = {},