Registry / testing / mock-match-media

mock-match-media

JSON →
library1.0.3jsnpmunverified

mock-match-media is a ponyfill for `window.matchMedia` designed for testing environments and server-side rendering (SSR) in Node.js. It allows developers to simulate various CSS media queries, including advanced Media Queries Level 5 features like range syntax (e.g., `(width < 150px)`), without a browser DOM. The current stable version is `1.0.3`, with releases focused on bug fixes and spec compliance. Key differentiators include its full compliance with the W3C Media Queries Level 5 specification, comprehensive support for event listeners (`addEventListener`, `removeEventListener`, `onchange`, `dispatchEvent`), and utility functions for cleaning up test states. It is written in TypeScript and primarily targets Node.js environments, requiring at least Node v20.19.0 for full ESM compatibility. The library offers both direct import and a polyfill mechanism.

npm install mock-match-media
INSTALL
IMPORT
SIG · MOCK-MATCH-MEDIA
M
mock-match-media
testingjavascriptv1.0.3
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

matchMedia, setMedia, cleanup
import { matchMedia, setMedia, cleanup } from 'mock-match-media';
const { matchMedia, setMedia, cleanup } = require('mock-match-media');
While CommonJS `require` works for most cases, modern Node.js environments (v20+) and TypeScript projects should prefer ESM imports. `mock-match-media` is built with TypeScript and ships types.
MediaQueryListEvent
import { MediaQueryListEvent } from 'mock-match-media';
const MediaQueryListEvent = require('mock-match-media').MediaQueryListEvent;
The `MediaQueryListEvent` class is exportable for custom event dispatching, though often implicitly handled by `matchMedia`.
Polyfill
import 'mock-match-media/polyfill';
require('mock-match-media').polyfill;
This import globally sets `matchMedia` and `MediaQueryListEvent` on `globalThis` (or `window` in browser-like environments), enabling usage without explicit imports for those symbols.

Demonstrates basic setup for testing with `mock-match-media` using Jest. It shows how to set media properties, evaluate queries, and test event listeners with proper cleanup.

import { matchMedia, setMedia, cleanup } from 'mock-match-media'; // Reset media state and listeners before each test to ensure isolation beforeEach(() => { cleanup(); }); describe('Media query matching', () => { it('should correctly match simple queries', () => { setMedia({ width: 50, type: 'screen', orientation: 'landscape', prefersColorScheme: 'light', }); expect(matchMedia('(min-width: 250px)').matches).toBe(false); expect(matchMedia('(width > 40px)').matches).toBe(true); setMedia({ width: 500, // Only redefine changed properties }); expect(matchMedia('(width > 250px)').matches).toBe(true); }); it('should support event listeners', () => { const listener = jest.fn(); const matcher = matchMedia('(min-width: 250px)'); matcher.addEventListener('change', listener); setMedia({ width: 100 }); expect(listener).not.toHaveBeenCalled(); // matches hasn't changed setMedia({ width: 1000 }); expect(listener).toHaveBeenCalledWith(expect.objectContaining({ matches: true })); matcher.removeEventListener('change', listener); listener.mockClear(); setMedia({ width: 100 }); expect(listener).not.toHaveBeenCalled(); // listener removed }); });
Debug
Known issues
breakingVersion 1.0.0 significantly updated Node.js version support. Projects on older Node versions (e.g., <20.19.0) will encounter compatibility issues, especially with ESM imports.
fix
Ensure your project uses Node.js v20.19.0 or higher. For older Node versions, consider staying on v0.x or upgrading your Node.js runtime.
affects: >=1.0.0
breakingThe `setMedia` function parameters `height`, `width`, `deviceHeight`, and `deviceWidth` now expect numbers instead of strings. This change was introduced in v1.0.0 due to an internal library update to `media-query-fns` for CSS Media Queries Level 5 support.
fix
Update all calls to `setMedia` that pass string values for these properties to use numbers instead (e.g., `width: '500px'` becomes `width: 500`).
affects: >=1.0.0
breakingFeature names passed to `setMedia` for complex queries may have changed from kebab-case to camelCase in v1.0.0. This aligns with the new `media-query-fns` dependency, supporting advanced CSS Media Queries Level 5.
fix
Review your `setMedia` calls and convert kebab-case feature names (e.g., `min-width`) to camelCase (e.g., `minWidth`). Consult the `media-query-fns` documentation for exact parameter names if issues persist.
affects: >=1.0.0
gotchaWhen using `addEventListener` with `mock-match-media`, changes to media properties via `setMedia` will only trigger the listener if the `matches` property of the `MediaQueryList` actually changes. If the media query still evaluates to the same boolean result, no event will be dispatched.
fix
Design tests to specifically change media conditions in a way that flips the `matches` state of the relevant media query to ensure listeners are properly tested.
affects: >=0.1.0
deprecatedThe `addListener` and `removeListener` methods on the `MediaQueryList` object are deprecated in favor of `addEventListener` and `removeEventListener`. While `mock-match-media` supports the deprecated methods, it's best practice to use the modern event API.
fix
Migrate any usage of `addListener` and `removeListener` to `addEventListener` and `removeEventListener` respectively, as per standard Web API recommendations.
affects: >=0.1.0
Errors
Common errors & fixes
ReferenceError: TextEncoder is not defined
Older JSDOM environments or Node.js versions might not provide `TextEncoder` globally, leading to runtime errors when `mock-match-media` (or its dependencies) tries to use it.
fix
For `mock-match-media@v1.0.1` and newer, this should be automatically handled. For older versions or specific environments, manually polyfill `TextEncoder` globally, for example, by adding `Object.assign(globalThis, { TextEncoder });` in your test setup file.
TypeError: setMedia is not a function
This usually happens when `setMedia` is not correctly imported or accessed from the `mock-match-media` package. It might be due to incorrect destructuring or trying to access it from `window.matchMedia` after polyfilling.
fix
Ensure `setMedia` is explicitly imported using named import: `import { setMedia } from 'mock-match-media';`. Note that `setMedia` is *not* part of the global polyfill; only `matchMedia` and `MediaQueryListEvent` are.
Error [ERR_REQUIRE_ESM]: require() of ES Module ... mock-match-media/dist/index.js from ... not supported.
Attempting to `require()` an ESM-only module in a CommonJS context, often due to Node.js version or project configuration. Version 1.0.0 and above have stricter ESM requirements.
fix
Upgrade your Node.js to v20.19.0 or higher and ensure your project is configured for ESM (e.g., `"type": "module"` in `package.json`). Alternatively, convert your `require()` statements to `import` statements if your environment supports it.
Upgrade
Version history
1.0.3latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources
mock-match-media — npm install mock-match-media · libregistry