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-mediaVerified import paths — ran on the pinned version, not inferred.
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.
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.
Update all calls to `setMedia` that pass string values for these properties to use numbers instead (e.g., `width: '500px'` becomes `width: 500`).
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.
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.
Migrate any usage of `addListener` and `removeListener` to `addEventListener` and `removeEventListener` respectively, as per standard Web API recommendations.
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.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.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.
No dependency data recorded yet.