harden(media-query): no-op the fallback when neither API exists

Guard the deprecated addListener/removeListener fallback with a
typeof check so a hypothetical MediaQueryList exposing neither the
modern nor the legacy API silently no-ops instead of re-introducing the
crash this helper exists to prevent. Add a test for the neither-API
case. (Follow-up from review.)
This commit is contained in:
Víctor Falcón 2026-07-05 18:57:28 +02:00
parent 8df1990617
commit 5f3d22b3aa
2 changed files with 21 additions and 2 deletions

View File

@ -28,6 +28,18 @@ describe('addMediaQueryListener', () => {
expect(addListener).toHaveBeenCalledWith(handler);
});
it('does not throw when neither API is present', () => {
expect(() =>
addMediaQueryListener(
fakeMql({
addEventListener: undefined,
addListener: undefined,
}),
() => {},
),
).not.toThrow();
});
});
describe('removeMediaQueryListener', () => {

View File

@ -18,7 +18,12 @@ export function addMediaQueryListener(
return;
}
mql.addListener(handler);
// Deprecated fallback for Safari <14 / legacy browsers. Guarded so a
// hypothetical MediaQueryList exposing neither API no-ops instead of
// re-introducing the crash this helper exists to prevent.
if (typeof mql.addListener === 'function') {
mql.addListener(handler);
}
}
export function removeMediaQueryListener(
@ -31,5 +36,7 @@ export function removeMediaQueryListener(
return;
}
mql.removeListener(handler);
if (typeof mql.removeListener === 'function') {
mql.removeListener(handler);
}
}