diff --git a/src/useMatchMedia.spec.ts b/src/useMatchMedia.spec.ts index 222f326..d2cfef6 100644 --- a/src/useMatchMedia.spec.ts +++ b/src/useMatchMedia.spec.ts @@ -71,4 +71,37 @@ describe('useMatchMedia()', () => { expect(result.current).toBe(false); }); + + itIfWindowDefined('should update the flag when the listener is called (legacy)', () => { + let matches = true; + const addListener = vi.fn(); + const removeListener = vi.fn(); + + const mql = { + get matches() { + return matches; + }, + addListener, + removeListener, + }; + + window.matchMedia = vi.fn().mockReturnValue(mql); + + let listener: EventListener; + addListener.mockImplementationOnce((_type, currentListener) => { + listener = currentListener; + + return () => null; + }); + + const { result } = renderHook(() => useMatchMedia('screen and (min-width: 1024px')); + + act(() => { + matches = false; + const mediaQueryListEvent = new MediaQueryListEvent('change', { matches }); + listener(mediaQueryListEvent); + }); + + expect(result.current).toBe(false); + }); }); diff --git a/src/useMatchMedia.ts b/src/useMatchMedia.ts index 605b539..78a8dd5 100644 --- a/src/useMatchMedia.ts +++ b/src/useMatchMedia.ts @@ -21,10 +21,13 @@ export default function useMatchMedia(query: string): boolean | null { return undefined; } - mql.addEventListener('change', handleMql); + const addEventListener = mql.addEventListener || mql.addListener; + const removeEventListener = mql.removeEventListener || mql.removeListener; + + addEventListener('change', handleMql); return () => { - mql.removeEventListener('change', handleMql); + removeEventListener('change', handleMql); }; }, [mql, handleMql]);