Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

vitest-matchmedia-mock

nggepe20.3kISC2.0.3TypeScript support: included

mocking window.matchmedia with vitest

mock, matchmedia, vitest

readme

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);
  });
});