🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
Book a DemoInstallSign in
Socket

vitest-matchmedia-mock

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vitest-matchmedia-mock

mocking window.matchmedia with vitest

2.0.3
latest
Source
npm
Version published
Weekly downloads
5.1K
0.42%
Maintainers
1
Weekly downloads
 
Created
Source

Vitest MatchMediaMock

codecov NPM Version NPM Downloads

how to import:

import MatchMediaMock from 'vitest-matchmedia-mock'

Usage example

describe('your test', () => {
  let matchMediaMock = new MatchMediaMock();
  afterAll(() => {
    matchMediaMock.clear();
  });
});

Use Media Query

Example implementation

export const myImplementation = () => {
  const myMediaMatcher = window.matchMedia('(prefers-color-scheme: dark)');
  myMediaMatcher.addEventListener('change', (ev) => {
    console.log(ev.matches);
  });

  return myMediaMatcher.matches;
};

Test

describe('your test', () => {
  let matchMediaMock = new MatchMediaMock();

  afterEach(() => {
    matchMediaMock.clear();
  });

  afterAll(() => {
    matchMediaMock.destroy();
  });

  test('matches immediately', () => {
    matchMediaMock.useMediaQuery('(prefers-color-scheme: dark)');
    const response = myImplementation();

    expect(response).toBe(true);
  });

  test('doesnt match immediately', () => {
    matchMediaMock.useMediaQuery('(prefers-color-scheme: light)');
    const response = myImplementation();

    expect(response).toBe(false);
  });

  test('fires change event with match', () => {
    myImplementation();
    matchMediaMock.useMediaQuery('(prefers-color-scheme: dark)');

    expect(console.log).toHaveBeenCalledWith(true);
  });

  test('fires change event with mismatch', () => {
    myImplementation();
    matchMediaMock.useMediaQuery('(prefers-color-scheme: light)');

    expect(console.log).toHaveBeenCalledWith(false);
  });
});

Keywords

mock

FAQs

Package last updated on 11 Apr 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts