Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't call window.matchMedia if it doesn't exist #161

Merged
merged 1 commit into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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