Test utility to mock `window.matchMedia` for JSDOM environments.

Overview

mock-match-media

Test utility for mocking window.matchMedia in JSDOM environments.

JSDOM doesn't provide support for window.matchMedia, which means testing it in Jest is pretty hard to do. Though the official documentation offers a workaround, that solution doesn't allow us to simulate changes to resolved media query values or trigger event listeners.

This utility mocks out the unsupported window.matchMedia function for a fully mocked substitution, with support for:

  • Creating a MediaQueryList via window.matchMedia
  • Changing the value of media states using a mocked state
  • Observing changes to media states with addEventListener, addListener, and onchange
  • Removing event listeners with removeEventListener and removeListener
  • Dispatching explicit events using dispatchEvent
  • Automatic environment cleanup between tests in Jest

Usage

import { mockMedia } from '@raymondwang/mock-match-media';

it('should alert listeners when the user’s OS enters dark mode', () => {
  const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  const spy = jest.fn();
  mediaQueryList.addEventListener('change', spy);
  // Mock the media state to indicate that the user prefers dark mode:
  mockMedia({ 'prefers-color-scheme': 'dark' });
  // Updating the mocked media state should call all listeners with changes:
  expect(spy).toHaveBeenCalledWith(expect.objectContaining({ matches: true }));
});

See MDN for more examples on testing media queries.

API

This library exports three methods:

mockMedia

Sets the value of a media feature in the mocked environment. For example, to simulate a device with a width of 1200px and a height of 800px:

mockMedia({
  width: '1200px',
  height: '800px',
});

clearMedia

Clears the mocked environment to its default values, without removing the mock. In Jest, this is called automatically in each afterEach block by default.

restoreMedia

Calls clearMedia and restores the original value of window.matchMedia. In Jest, this is called automatically in each afterAll block by default.

Support & caveats

This library is built against css-mediaquery, which follows the Media Queries Level 3 spec.

This means it has out-of-the-box support for the following media features:

  • type (all | screen | print)
  • any-hover
  • any-pointer
  • aspect-ratio
  • color-index
  • color
  • device-aspect-ratio (deprecated)
  • device-height (deprecated)
  • device-width (deprecated)
  • display-mode
  • grid
  • height (min-, max-)
  • hover
  • inverted-colors
  • monochrome
  • orientation
  • pointer
  • prefers-color-scheme
  • prefers-contrast
  • prefers-reduced-data
  • prefers-reduced-motion
  • prefers-reduced-transparency
  • resolution
  • scan
  • width (min-, max-)

It also supports compound media queries, like 'screen and (min-width: 1200px) and (max-width: 800px)', or (prefers-color-scheme: dark), (monochrome)'.

However, it does not support features proposed in the Level 4 draft, such as comparison operators (e.g. (400px < width < 1000px)) or combining media features with the or keyword (e.g. (pointer) or (hover)).

You might also like...

Linely is inspired by LocalStack. Goal of this tool is to create a mock service for LINE.

Linely Linely is inspired by LocalStack. Goal of this tool is to create a mock service for LINE. Setup Docker docker run -d -p 3000:3000 dyoshikawa/li

Jan 24, 2022

NiseLine is inspired by LocalStack. Goal of this tool is to create a mock service for LINE.

NiseLine NiseLine is inspired by LocalStack. Goal of this tool is to create a mock service for LINE. Getting Started Launch NiseLine server. docker ru

Jan 24, 2022

NiseLine is inspired by LocalStack. Goal of this tool is to create a mock service for LINE.

NiseLine is inspired by LocalStack. Goal of this tool is to create a mock service for LINE.

NiseLine NiseLine is inspired by LocalStack. Goal of this tool is to create a mock service for LINE. Getting Started Launch NiseLine server by Docker

Jul 29, 2022

A social-media mock app for the ones who love to read - and maybe show it off

🐋 🐳 Cachalote 🐳 🐋 Share what you are reading and find people who also likes it - or not! What does it do? This app focuses on three main questions

May 22, 2022

The Remix Stack for deploying to Vercel with testing, linting, formatting, structure and mock for 3rd party API integration.

The Remix Stack for deploying to Vercel with testing, linting, formatting, structure and mock for 3rd party API integration.

Remix DnB Stack See it live: https://dnb-stack.vercel.app/ Learn more about Remix Stacks. npx create-remix --template robipop22/dnb-stack What's in th

Dec 13, 2022

LIFF Mock is a LIFF Plugin that make testing your LIFF app easy.

LIFF Mock LIFF Mock is a LIFF Plugin that make testing your LIFF app easy. ※ LIFF Plugin feature is available since LIFF SDK v2.19.0. Usage NPM $ npm

Dec 2, 2022

mock APIs, intelligently, with context, and perform other stuff as well

@sasta-sa/project mock APIs, intelligently, with context, and perform other stuff as well 😄 Setting up Clone the project git clone https://github.com

Jan 27, 2022

A mock Twitter page implemented without, partially with, and then with a design system.

Design Systems Workshop A mock Twitter page implemented without, partially with, and then with a design system. Setup Install npm dependencies, then s

Dec 8, 2022

A utility for creating toggleable items with JavaScript. Inspired by bootstrap's toggle utility. Implemented in vanillaJS in a functional style.

LUX TOGGLE Demo: https://jesschampion.github.io/lux-toggle/ A utility for creating toggleable dom elements with JavaScript. Inspired by bootstrap's to

Oct 3, 2020
Owner
Raymond Wang
Raymond Wang
A lightweight (~850 B) library for easy mac/window shortcut notation. kbd-txt convert shortcut text depending on the type of OS (window/linux/mac).

kbd-txt A lightweight (~850 B) library for easy mac/window shortcut notation. kbd-txt convert shortcut text depending on the type of OS (window/linux/

Minung Han 6 Jan 1, 2023
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Babel-plugin-amd-checker - Module format checking plugin for Babel usable in both Node.js the web browser environments.

babel-plugin-amd-checker A Babel plugin to check the format of your modules when compiling your code using Babel. This plugin allows you to abort the

Ferdinand Prantl 1 Jan 6, 2022
End-to-end encrypted environments

Welcome to the EnvKey v2 monorepo! All EnvKey's open source code lives here. End-to-end encrypted environments Fixes configuration sprawl and sloppy s

EnvKey 360 Jan 1, 2023
Jester is a test-generation tool to create integration test code.

Code Generator for Integration Tests Introduction Welcome to Jester: An easy-to-use web application that helps you create and implement integration te

OSLabs Beta 54 Dec 12, 2022
Simple Solid primitive unit test utility.

solid-primitive-test-util Simple Solid primitive unit test utility. Install pnpm add solid-primitive-test-util -D Example Basic Usage Let's say we hav

Robert Soriano 2 Mar 21, 2022
Base-mock-api - Repo to storage my fake api's to use in my 2022 projects.

Base Mock API's Project made 100% with JavaScript, with the objective of creating endpoints to use in projects. Prerequisites Before you begin, ensure

Arthur Cabral 0 Nov 20, 2022
Quickly create an interactive HTML mock-up by auto sourcing lorem ipsum/images generators, with minimal html markup, and no server side code

RoughDraft.js v0.1.5 Quickly mockup / prototype HTML pages with auto-generated content, without additional JavaScript or server side code. <section>

Nick Dreckshage 464 Dec 21, 2022