npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mock-match-media

v0.4.3

Published

mock window.matchMedia for tests or node

Downloads

130,323

Readme

Simple server-side compatible substitution for window.matchMedia() based on css-mediaquery.

  1. What is mock-match-media?
  2. Usage
    1. Listeners
    2. Cleanup
      1. cleanupListeners
      2. cleanupMedia
      3. cleanup
    3. Polyfill
    4. Other features
      1. once event listeners
      2. .dispatchEvent & MediaQueryListEvent
      3. .onchange
      4. Interactions between multiple listeners
    5. ESM
  3. How to use with other libraries
    1. Jest
    2. NextJS

What is mock-match-media?

mock-match-media is a ponyfill for window.matchMedia but for Node.

This mock is fully compliant with the spec (see doc on MDN or Other features).

Node CI tests

We currently support Node v12, v14, v16, v18 and v19.

It's also coded in TypeScript.

Usage

const { matchMedia, setMedia } = require("mock-match-media");

// Define current media
setMedia({
    width: "50px",
    type: "screen",
    orientation: "landscape",
    "prefers-color-scheme": "light",
});

matchMedia("(min-width: 250px)").matches;
// > false
matchMedia("(min-width: 40px)").matches;
// > true

// Only redefine what changed
setMedia({
    width: "500px",
});

matchMedia("(min-width: 250px)").matches;
// > true

Listeners

mock-match-media also supports even listeners:

const { matchMedia, setMedia } = require("mock-match-media");

setMedia({
    width: "50px",
});

const listener = (event) => console.log(event.matches);

const matcher = matchMedia("(min-width: 250px)");

matcher.addEventListener("change", listener);
// And also the deprecated version
// matchMedia("(min-width: 250px)").addListener(event => console.log(event.matches));

setMedia({
    width: "100px",
});
// outputs nothing because `matches` hasn't changed

setMedia({
    width: "1000px",
});
// outputs `true`

matcher.removeEventListener("change", listener);

setMedia({
    width: "100px",
});
// outputs nothing because the listener is removed

Cleanup

mock-match-media provides 3 cleanup functions:

const { cleanupListeners, cleanupMedia, cleanup } = require("mock-match-media");

cleanupListeners

cleanupListeners clears all listeners called via matchMedia().addListener() or matchMedia().addEventListener() (to avoid calling in side effects).

cleanupMedia

cleanupMedia resets the state of the window set via setMedia().

cleanup

cleanup at the same time clears all listeners (like cleanupListeners), and clears the state of the window (like cleanupMedia).

Polyfill

If you don't want to change your code or to setup mocks with your testing library, you can do:

require("mock-match-media/polyfill");

And then global variables matchMedia and MediaQueryListEvent will be set. And thus, you won't have to import those (you'll still have to import setMedia, and the cleanup functions).

Other features

This library covers most of the aspects of matchMedia. In addition to the API presented above, it also supports:

once event listeners

const { matchMedia } = require("mock-match-media");

const mql = matchMedia("(min-width: 250px)");
mql.addEventListener("change", listener, { once: true }); // the listener will be removed after 1 received event

.dispatchEvent & MediaQueryListEvent

Like every other EventTarget, you can .dispatchEvent(event) to manually dispatch event (it’s not that useful to be honest, but as it’s in the spec, we implemented it).

const { matchMedia, MediaQueryListEvent } = require("mock-match-media");

const mql = matchMedia("(min-width: 250px)");
mql.dispatchEvent(new MediaQueryListEvent("change", { matches: false, media: "(custom-non-valid)" }));
// Works also with a regular event but it’s not recommended:
mql.dispatchEvent(new Event("change"));

.onchange

Like on any HTML element, you can attach a .onchange legacy event handler:

const { matchMedia } = require("mock-match-media");

const mql = matchMedia("(min-width: 250px)");
mql.onchange = listener;

Interactions between multiple listeners

We follow how browsers implemented interactions like:

const { matchMedia } = require("mock-match-media");

const mql = matchMedia("(min-width: 250px)");
mql.onchange = listener;
mql.addListener(listener);
mql.addEventListener("change", listener);
mql.addEventListener("change", listener, { once: true });

And all of those are tested.

ESM

We also ship 2 versions of this library:

  • one in CJS
  • one in ESM

This is also true for the polyfills, but the setup-jest file is only available in CJS (Jest doesn't work that well with ESM).

How to use with other libraries

Jest

In jest.setup.js, you only need to import mock-match-media/jest-setup (or mock-match-media/jest-setup.cjs depending on your config). It'll:

  • install the polyfill (for matchMedia and MediaQueryListEvent)
  • add a call to cleanup in afterAll to auto-cleanup your env in after each test/it.

You can set import jest-setup in setupFiles or in setupFilesAfterEnv in your jest config.

And then you can use setMedia in your tests.

You can find an example here that includes Jest, react testing library and react-scripts.

NextJS

You can find an example here for how to use mock-match-media with NextJS.