Skip to content

Commit

Permalink
Don't call window.matchMedia if it doesn't exist (#161)
Browse files Browse the repository at this point in the history
Co-authored-by: Rogin Farrer <[email protected]>
  • Loading branch information
roginfarrer and Rogin Farrer authored Oct 23, 2023
1 parent 8c2a07b commit a12f2e4
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changeset/blue-moons-impress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'react-collapsed': patch
---

Do not call window.matchMedia if it does not exist. Fixes errors thrown in environments like JSDOM.
4 changes: 4 additions & 0 deletions packages/react-collapsed/src/utils/usePrefersReducedMotion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
15 changes: 0 additions & 15 deletions packages/react-collapsed/tests/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {},
Expand Down

0 comments on commit a12f2e4

Please sign in to comment.